Get only inner text from webelemnt

。_饼干妹妹 提交于 2021-02-20 02:17:20

问题


I want to get only innerText from a webelement. I want to get only "Name" from the anchor tag.I have access to webdriver element associated with tag in below example(anchorElement). I tried anchorElement.getText() and anchorElement.getAttribute("innerText"). Both return me "Name, sort Z to A". What should I do here ?

<a id="am-accessible-userName" href="javascript:void(0);" class="selected">
Name 
<span class="util accessible-text">, sort Z to A</span> 
<span class="jpui iconwrap sortIcon" id="undefined" tabindex="-1"> 
<span class="util accessible-text" id="accessible-"></span> 
<i class="jpui angleup util print-hide icon" id="icon-undefined" aria-hidden="true"></i>
</span>
</a>

回答1:


A bit of Javascript can pick out just the child text node:

RemoteWebDriver driver = ...
WebElement anchorElement = driver.findElement(By.id("am-accessible-userName"));
String rawText = (String) driver.executeScript(
    "return arguments[0].childNodes[0].nodeValue;", 
    anchorElement);

So anchorElement is passed into the Javascript as arguments[0] there.

Clearly childNodes[0] is assuming where the text node is. If that's not safe, you could iterate the childNodes too, perhaps checking for childNode.nodeName === "#text"




回答2:


As per the HTML the desired element is a Text Node and also the First Child Node of the <a> tag. So to extract the text Name you can use the following code block :

  • Java Binding Art :

    WebElement myElement = driver.findElement(By.xpath("//a[@class='selected' and @id='am-accessible-userName']"));
    String myText = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", myElement);
    System.out.println(myText);
    



回答3:


The text alone could be obtained by using proper javascript code to iterate through child nodes of a given weblement and then returning text if the current node is a text node. Note: A trimmed value of node text will be returned.

public String getInnerText(WebDriver e, String xpathStr){
WebElement ele = e.findElement(By.xpath(xpathStr));
        return ((String) ((JavascriptExecutor) e).executeScript("var children = arguments[0].childNodes;\n" +
                "for(child in children){\n" +
                "   if(children[child].nodeName === \"#text\"){" +
                "  return children[child].nodeValue };\n" +
                "}" , ele )).trim(); 
}


来源:https://stackoverflow.com/questions/50162871/get-only-inner-text-from-webelemnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!