我正在尝试提取元素的人口数字/文本。
我尝试与 parent 联系,但显示错误。我正在尝试从此页表中获取中国的人口https://en.wikipedia.org/wiki/China
代码试用:
WebElement dateBox7 = driver.findElement(By.xpath("//*[contains(text(),'Population')]/parent::tr//td/a[text()]"));
错误:
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
我已经尝试过 //*[contains(text(),'2016 年估计')]/ancestor::tr/td/text()[1]
这个 xpath 它显示了人口DOM。但是在 selenium 中它显示错误:
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "//*[contains(text(),'2016 estimate')]/ancestor::tr/td/text()[1]" is: [object Text]. It should be an element.
为什么它不起作用?
最佳答案
尝试使用这个 xpath
"//*[contains(.,'Population')]/parent::tr//th/a[text()]"
请注意,有两个更改:td
-> th
和 [contains(text(),'Population')]
-> [包含(.,'人口')]
。
搜索[contains(.,'Population')]
时,“点”表示搜索元素内部的所有文本(包括后代),而“text()”将仅搜索元素的直接纹理内容。
编辑:
根据您的评论,尝试这个 xpath:
"//*[contains(.,'Population')]/parent::tr/following-sibling::tr[1]/td"
编辑#2:
关于javascript - 如何通过 Java 使用 Selenium 从 en.wikipedia.org 中提取一个国家的人口数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56338993/