使用Rcurl和XML从一帧HTML获取表格

时间:2014-04-04 21:05:17

标签: html r web-scraping rcurl

如何从http://portal.inep.gov.br/basica-censo-escolar-matricula

中搜索一个表格

该表在第14帧内。

我必须选择拥有数据的状态:例如ACRE并点击“consultar”

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用Selenium

执行此操作
require(RSelenium)
appURL <- "http://portal.inep.gov.br/basica-censo-escolar-matricula"
RSelenium::startServer()
remDr <- remoteDriver()
remDr$open()
remDr$navigate(appURL)

# find iframes
iframes <- remDr$findElements("css selector", "iframe")
iframes[[1]]$highlightElement() # visual check
remDr$switchToFrame(iframes[[1]])

# get Estado selections
webElems <- remDr$findElements("css selector", "#uf option")
estadoNames <- sapply(webElems, function(x){x$getElementText()[[1]]})
webElem <- webElems[[which(estadoNames == "ACRE")]]
webElem$clickElement()

# click the submit button
webElem <- remDr$findElement("id", "btnSubmit")
webElem$clickElement()

# find the table
webElem <- remDr$findElement("css selector",".Resultado")
webElem$highlightElement() # visual confirmation
tableHTML <- webElem$getElementAttribute("outerHTML")[[1]]

remDr$close()
remDr$closeServer()

答案 1 :(得分:0)

那一个特别棘手。

enter image description here

当我右键单击IFRAME部分并在Chrome中执行Inspect Element时,看起来它的生成方式很难以编程方式获取。

我可以通过右键单击<html xmlns="http://…行,选择&#34;编辑为html&#34;来提取表格。然后做一个全选,复制&amp;粘贴到Sublime Text并保存为HTML文件(例如:http://rud.is/dl/22872999.html)。

你可以在Firefox中做同样的事情(更简单的IMO),右击桌面框并进行右键单击/查看源,然后复制&amp;将HTML粘贴到文本编辑器(如Sublime Text)并保存到HTML文件中。

您应该能够使用标准R表/ XML提取代码对以这种方式保存的文件进行操作。

它远非最佳解决方案,但它有效。我希望其他人采用更具程序性的方法。