【问题标题】:How to store results from a loop for webscraping using rvest in R如何在 R 中使用 rvest 存储循环的结果以进行网络抓取
【发布时间】:2021-05-16 17:12:36
【问题描述】:

我正在尝试从同一网站导入数据库,但在不同的选项卡中。

# webscraping para idh

algo <- c(1996:2017)

idh_link <- c(paste0("https://datosmacro.expansion.com/idh?anio=", 1996:2017))
final <- vector(length = length(idh_link))

for (i in seq_along(algo)) {
idh_desc <- read_html(idh_link[i])

pais <- idh_desc %>% 
  html_nodes("td:nth-child(1), .header:nth-child(1)") %>% 
  html_text()

idhaño <- idh_desc %>% 
  html_nodes("td:nth-child(2), .header:nth-child(2)") %>% 
  html_text()

final[i] <- tibble(pais, idhaño)
}

在这种情况下,它只从第一个链接中恢复信息,而不是在循环结束时创建小标题(想法是对所有小标题进行内部连接)。

我正在使用library(rvest) 进行网页抓取

【问题讨论】:

    标签: r loops web-scraping rvest tibble


    【解决方案1】:

    向量无法存储 data.frames/tibbles。向量只能存储原子对象,如整数、字符串等。

    要存储一系列数据帧,最好使用列表。

    algo <- c(1996:2017)
    
    idh_link <- c(paste0("https://datosmacro.expansion.com/idh?anio=", 1996:2017))
    #data structure to store a series of data frames
    final <- list()
    
    for (i in seq_along(algo)) {
       idh_desc <- read_html(idh_link[i])
       
       pais <- idh_desc %>% 
          html_nodes("td:nth-child(1), .header:nth-child(1)") %>% 
          html_text()
       
       idhaño <- idh_desc %>% 
          html_nodes("td:nth-child(2), .header:nth-child(2)") %>% 
          html_text()
       
       #name the list elements with the year information
       final[[as.character(algo[i])]] <- tibble(pais, idhaño)
    
       #add a pause so not to "attack" the server
       Sys.sleep(1)
    }
    

    要组合存储在列表中的所有数据框,我建议使用 dplyr 包中的 bind_rows()bind_cols()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 2018-02-15
      • 2019-07-21
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多