javascript - 如何通过 Java 使用 Selenium 从 en.wikipedia.org 中提取一个国家的人口数据

标签 javascript java selenium-webdriver xpath webdriverwait

我正在尝试提取元素的人口数字/文本。

我尝试与 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:

有关 Xpath 定位器的教程,请参阅 here有关该主题的免费类(class),请参阅 here .

关于javascript - 如何通过 Java 使用 Selenium 从 en.wikipedia.org 中提取一个国家的人口数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56338993/

相关文章:

python - Selenium:从日历中选择日期

java - 在哪里可以找到 Java 中浏览器首选项的 ChromeDriver 常量?

javascript - Vue 不会在 'indirectly' 更改表达式的值时更新 DOM

javascript - 如何从各种 AJAX 调用中积累数据?

JavaScript:当我尝试使用 DOM 时,我的 for 循环似乎不起作用

javascript - 无显示改变输入方式 :none

java - Maven 多模块项目结构

java - 只有一个同步点是否有可能出现死锁?

Java:如何在中断后无限期地让线程回到 sleep 状态?

java - Selenium : How to click an element in the chat page whenever the new chat is available