【问题标题】:RSelenium: Can't extract piece of text from tableRSelenium:无法从表格中提取一段文本
【发布时间】:2016-10-21 08:48:38
【问题描述】:

查看this 网页。我想提取文本元素“2013”​​。我为此使用 RSelenium,但如果有人知道如何使用任何其他也可以的软件包来做到这一点。我当前的脚本如下:

startServer()
remDr <- remoteDriver(browserName="chrome")
remDr$open(silent=T)
remDr$navigate(as.character(url))
remDr$findElement("css selector","#crosstable > table > tbody > tr:nth-child(2) > th:nth-child(2)")$getElementText()

这会产生以下错误:

Error:   Summary: NoSuchElement
Detail: An element could not be located on the page using the given search parameters.
class: org.openqa.selenium.NoSuchElementException

我注意到的第一件事是无法使用 selectorgadget 选择这段短文本。所以我想在源代码中查找这段文本并复制其特定的选择器路径:#crosstable &gt; table &gt; tbody &gt; tr:nth-child(2) &gt; th:nth-child(2)。但正如错误所示,这不起作用。

我是网络抓取的新手,几乎没有 html 知识,因此欢迎提供有关如何从表格中提取文本“2013”​​的任何线索。

编辑 - 我找到了方法

startServer()
remDr <- remoteDriver(browserName="chrome")
remDr$open(silent=T)
remDr$navigate(as.character(url))
webElem <- remDr$findElement("id", "content_iframe")
remDr$switchToFrame(webElem)
webElem <- remDr$findElement("id", "passthrough")
remDr$switchToFrame(webElem)

remDr$findElement("xpath",'//*[@id="crosstable"]/table/tbody/tr[2]/th[2]')$getElementText()

【问题讨论】:

  • 表格位于 iframe 中,而 iframe 本身位于 iframe 中。您将需要使用 switchToFrame 方法来访问相应的框架以引用表格元素。
  • 或者您也可以通过apps.who.int/gho/athena/data/GHO/…:* 直接访问表格框
  • 您还可以下载多种格式的数据,例如 csv

标签: html r selenium web-scraping rselenium


【解决方案1】:
webElem <- remDr$findElement("id", "content_iframe")

remDr$switchToFrame(webElem)

remDr$findElement("css selector","#crosstable > table > tbody > tr:nth-child(2) > th:nth-child(2)")$getElementText()

/* perform operation */

remDr$switchToFrame(NULL)

【讨论】:

  • 感谢您的回答。但是,我在findElement() 部分收到错误“NoSuchElement”。
  • 切换到“content_iframe”框架后,我应该再次切换到“passthrough”框架,然后才能访问该元素。
  • 是的,您需要通过多个(嵌套)框架切换才能访问该元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 2023-03-12
相关资源
最近更新 更多