Cannot get text using text() in XPath

霸气de小男生 提交于 2019-12-13 04:08:35

问题


Here is part of html code:

<td class="audit-context-break-word text-left" nowrap="nowrap">
<b class="ng-binding">PONumber</b></td>
<td class="audit-context-break-word text-left ng-binding">20202022  02_001  </td>

I need to get only text inside (expected value: 20202022 02_001) I tried following variants:

By.xpath("/descendant::*[.='PONumber']/../descendant::*[@class=\"audit-context-break-word text-left ng-binding\"]/text()")
By.xpath("/descendant::*[.='PONumber']/../following::text()[1]")

The issue is that in FirePath selected text is found, but not in test. It is failed due to timeout exception, because element is not found

What is the reason of the failure?


回答1:


You can use following-sibling to write the Xpath.

WebElement element=driver.findElement(By.xpath("//td[b[contains(text(),'PONumber')]]/following-sibling::td"));
        String text = element.getText();
        System.out.println(text);
  1. I'm identifying appropriate web element on the webpage and saving it in web element.

  2. Using getText() method to obtain text from that web Element and saving it in string

  3. Print that string text




回答2:


following-sibling is something you should use:

driver.findElement(By.xpath("//td[b = 'PONumber']/following-sibling::td")).getText();



回答3:


Selenium cannot evaluate text() function of xpath. you can run javascript and can get result. run following javascript in your program:

document.evaluate("//span[@class='tableNode']/text()[preceding-sibling::br and following-sibling::br]", document, null, XPathResult.STRING_TYPE, null).stringValue;

if you use Python or Java, i can present




回答4:


I had a similar problem where an element was visible but tests wouldn't pass on isTextPresent. When I checked the source code, it was

  • 2-1180 \&\nbsp CITY 2
  • , whereas the test was looking for "2-1180 CITY 2". Check if you have a similar problem too. Let us know what works for you, would be interested in knowing.

    Note: do not downvote, just trying to help.



    来源:https://stackoverflow.com/questions/32907161/cannot-get-text-using-text-in-xpath

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