【发布时间】:2018-07-05 20:20:08
【问题描述】:
我想设置一个循环来自动跨多个页面进行一些网页抓取。到目前为止,这是我一次迭代的代码:
s <- html_session("https://www.hcdn.gob.ar/proyectos/resultados-buscador.html?")
s <- s %>% jump_to("?pagina=5") %>% read_html()
new <- s %>% html_nodes('div.dp-metadata span') %>% html_text()
type.2 <- s %>% html_nodes('h4') %>% html_text()
title <- s %>% html_nodes('div.dp-texto') %>% html_text()
new <- gsub("Iniciado en: ", "", new)
new <- gsub("Fecha: ", "", new)
new <- gsub("Expediente Diputados:", "", new)
new <- gsub("Expediente Senado:", "", new)
new<- new [-c(3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 67, 71, 75, 79)]
chamber <- new[c(1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58)]
billnum <- new[c(2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59)]
fecha <- new[c(3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60)]
new2 <- data.frame(chamber, billnum, fecha, title, type.2)
应该改变的部分是“pagina=”后面的数字。但是,我尝试创建以下简化循环,但它只是返回了一个错误:
new4 <- data.frame(matrix(nrow=40, ncol=2))
colnames(new4) <- c("title", "type")
for (i in 1:2) {
s <- html_session("https://www.hcdn.gob.ar/proyectos/resultados-buscador.html?")
s <- s %>% jump_to("?pagina=", i) %>% read_html()
type.2 <- s %>% html_nodes('h4') %>% html_text()
title <- s %>% html_nodes('div.dp-texto') %>% html_text()
new4[i, 1] <- title
new4[i, 2] <- type.2
}
同样,这个仅抓取我需要的五个功能中的两个的简化循环不起作用并返回错误:f(init, x[[i]]) 中的错误:is.request(y) 不是 TRUE。我想在循环中运行 html_session() 和 jump_to() 命令有问题。我想知道如何在循环中自动执行此操作,以避免手动抓取数千页。
我什至尝试使用 lapply 创建一个向量,但我对我的函数编码不是很有信心,而且我看到的所有模板都是简单的 read_html() 命令,我不太确定我是怎么做的会将 html_session() 和 jump_to() 命令合并到一个函数中。
【问题讨论】:
标签: html r loops web-scraping