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

前端 未结 2 1441
温柔的废话
温柔的废话 2021-01-29 16:53
相关标签:
2条回答
  • 2021-01-29 17:10

    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);
                            });
    
    0 讨论(0)
  • 2021-01-29 17:18

    You are using the plural findElements, which gives you a list of elements. Using e.text against the list won't work because you can only use .text with a webobject.

    Use the singular version to get the first match on the page: driver.findElement()

    If you do need to get the text of only one element in a list, use e[0].text to get the text of the first element in the list.

    0 讨论(0)
提交回复
热议问题