Search code examples
javaseleniumselenium-webdriverxpathxpath-1.0

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?


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.