【问题标题】:Web scraping: Combining tables in for-loop in R网页抓取:在 R 中的 for 循环中组合表格
【发布时间】:2020-07-05 16:48:16
【问题描述】:

我正在使用循环从网站上抓取表格。无法弄清楚如何将表格组合成一个数据框。以下代码用于抓取一页的相关信息,但我不确定如何将新表添加到第一个(或预先存在的)。谢谢。

for (i in 1:10){
  
    link <- paste0("https://website.com/page",i)
    remDr$navigate(link)  

    # grab the html
    pg <- remDr$getPageSource() %>% .[[1]] %>%
         read_html()

    #grab the correct table
    table <- pg %>%
            html_nodes("table") %>%
            .[2] %>%
            html_table(fill = TRUE) %>%
            .[[1]] 
    
    # combine tables?
  
}

【问题讨论】:

    标签: r for-loop web-scraping


    【解决方案1】:

    如果要保留循环,请在循环体之前声明一个数据框,并在每次迭代时使用rbind 不断添加:

    big_df <- data.frame()
    
    for (i in 1:10){
    
      link <- paste0("https://website.com/page", i)
      remDr$navigate(link)  
    
      # grab the html
      pg <- remDr$getPageSource() %>% .[[1]] %>%
              read_html()
    
      # grab the correct table
       table <- pg %>%
                  html_nodes("table") %>%
                  .[2] %>%
                  html_table(fill = TRUE) %>%
                  .[[1]] 
    
      # combine tables?
      big_df <- rbind(big_df, table)
    }
    

    一种更好(更快)的方法是将循环体放在一个函数中,将其应用到1:10 以生成数据帧列表,然后使用data.table::rbindlist 将所有这些放在一起:

    df_list <- lapply(1:10, function (i) {
    
                 link <- paste0("https://website.com/page", i)
                 remDr$navigate(link)  
    
                 # grab the html
                 pg <- remDr$getPageSource() %>% .[[1]] %>%
                         read_html()
    
                 # grab the correct table
                 table <- pg %>%
                            html_nodes("table") %>%
                            .[2] %>%
                            html_table(fill = TRUE) %>%
                            .[[1]]
    
                 return(table)
               })
    
    big_df <- data.table::rbindlist(df_list)
    

    【讨论】:

    • 第二个解决方案需要一个右括号,但除此之外它就像一个魅力。非常感谢!!
    • 我很高兴它有所帮助,感谢您指出错误 - 立即修复它。
    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 2021-09-18
    • 2017-08-06
    • 1970-01-01
    • 2022-01-24
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多