Search code examples
seleniumxpathtestngservice-locator

Cannot get text using text() in XPath


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?


Solution

  • 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