[Solved] How to get the text of an anchor tag selected by xPath() using selenium and Mocha


You can try this approach:

driver.findElement(By.xpath("//a[contains(@class, 'user-name m-r-sm text-muted welcome-message')]")).getText().then(function(text){
                           console.log("Username : " + text);
                        });
  • you only need to search via findElement (not findElements)
  • and directly extract the text before the function part

UPDATE:

Sometimes the object is not really hidden, but also not in the viewport, then gettext() also returns an empty String.
To check try the following:

driver.findElement(By.xpath("//a[contains(@class, 'user-name m-r-sm text-muted welcome-message')]")).getAttribute("innerText").then(function(text){
                           console.log("Username : " + text);
                        });

4

solved How to get the text of an anchor tag selected by xPath() using selenium and Mocha