简体   繁体   English

通过 xpath 查找子元素

[英]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.这段代码的问题是 childInnerHtml 给了我错误的结果。 I scrape numbers and they are equal.我抓取数字,它们是相等的。

I even suppose that my code is equal to driver.findElement(By.xpath .我什至假设我的代码等于driver.findElement(By.xpath

Could you tell me whether my comment really finds a child or what to correct?你能告诉我我的评论是否真的找到孩子或纠正什么?

Child XPath need to be a relative XPath. Normally this means the XPath expression is started with a dot .孩子 XPath 需要是亲戚XPath。通常这意味着 XPath 表达式以点开头. to make this XPath relative to the node it applied on.使这个 XPath对于它应用的节点。 Ie 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.否则 Selenium 将从整个页面的顶部开始搜索给定的xpath (您传递给此方法的参数)。
So, if for example, the passed xpath is "//span[@id='myId']" it should be ".//span[@id='myId']" .因此,例如,如果传递的xpath"//span[@id='myId']"它应该是".//span[@id='myId']"
Alternatevely you can add this dot .或者,您可以添加此点. inside the parent.findElement(By.xpath(xpath));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.但是用点传递xpath是更简单和干净的方法。 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.特别是如果传递的xpath是像"(//div[@class='myClass'])[5]//input"这样的复杂表达式 - 在这种情况下,在此表达式之前自动添加一个点可能无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM