【问题标题】:Webscrape using for loop into data frame in RWebscrape使用for循环进入R中的数据框
【发布时间】:2023-03-28 02:23:01
【问题描述】:

我觉得我对此很了解,但找不到正确的解决方案。我想从多个页面中抓取表格并将结果保存到一个最终数据框中。所有表都将具有相同的结构。我的代码在下面带有一个循环示例(实际上可能有 1,000 页)。当我在单个页面上运行代码时,我可以获得结果,但我无法弄清楚循环或如何将循环结果保存到数据框中。看看我在下面做什么,任何帮助表示赞赏!

library(textreadr)
library(dplyr)
library(rvest)

for (event in (803:806)){
  url<-paste0('http://profightdb.com/cards/wwf/monday-night-raw-', event,'.html')
  webpage<-read_html(url)
  tbls_ls<-webpage %>%
    html_nodes('table') %>%
    .[[2]] %>%
    html_table(fill=TRUE)
}

【问题讨论】:

    标签: r loops dataframe web-scraping


    【解决方案1】:

    也许将结果保存为数据框列表。

    library(textreadr)
    library(dplyr)
    library(rvest)
    
    tbls_ls <- vector(4, mode="list") # Initialize the list
    i <- 1 # Initialize the index
    
    for (event in (803:806)){
      url <- paste0('http://profightdb.com/cards/wwf/monday-night-raw-', event,'.html')
      webpage <- read_html(url)
    
      tbls_ls[[i]] <- webpage %>%
        html_nodes('table') %>%
        .[[2]] %>%
        html_table(fill=TRUE)
    
      i <- i+1  # Update the index
    }    
    

    class(tbls_ls) # "list"
    names(tlbs_ls) <- 803:806  # Name the elements
    tbls_ls[1]
    $`803`
      no.                        match      match                           match duration
    1   1                     Yokozuna def. (pin)                     Koko B Ware    03:45
    2   2 Rick Steiner & Scott Steiner def. (pin) Executioner #1 & Executioner #2    03:00
    3   3           Shawn Michaels (c) def. (pin)                        Max Moon    10:30
    4   4               The Undertaker def. (pin)                  Damien Demento    02:26
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多