Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find child element by xpath

public WebElement findChildByXpath(WebElement parent, String xpath) {
    loggingService.timeMark("findChildByXpath", "begin. Xpath: " + xpath);

    String parentInnerHtml = parent.getAttribute("innerHTML"); // Uncomment for debug purpose.

    WebElement child = parent.findElement(By.xpath(xpath));

    String childInnerHtml = child.getAttribute("innerHTML"); // Uncomment for debug purpose.

    return child;
}

The problem with this code is that childInnerHtml gives me wrong result. I scrape numbers and they are equal.

I even suppose that my code is equal to driver.findElement(By.xpath.

Could you tell me whether my comment really finds a child or what to correct?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Child XPath need to be a relative XPath. Normally this means the XPath expression is started with a dot . to make this XPath relative to the node it applied on. I.e. to be relative to the parent node. Otherwise Selenium will search for the given xpath (the parameter you passing to this method) starting from the top of the entire page.
So, if for example, the passed xpath is "//span[@id='myId']" it should be ".//span[@id='myId']".
Alternatevely you can add this dot . inside the parent.findElement(By.xpath(xpath)); line to make it

WebElement child = parent.findElement(By.xpath("." + xpath));

But passing the xpath with the dot is more simple and clean way. Especially if the passed xpath is come complex expression like "(//div[@class='myClass'])[5]//input" – in this case automatically adding a dot before this expression may not work properly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading