繁体   English   中英

尝试在 R 中使用 for 循环从多个网页中抓取表格

[英]Trying to scrape a table from multiple webpages with a for loop in R

我正在尝试从不同 MLB 团队的多个网页中抓取信息。 这些是我试图从https://www.covers.com/sport/baseball/mlb/teams/main/miami-marlins/2019https://www.covers.com/sport/baseball/抓取的网站mlb/teams/main/cleveland-indians/2019 对于两个团队,我都试图从页面上的第 12 个表中抓取信息,然后将它们作为数据框连接在一起。 到目前为止我的代码看起来像这样

library(rvest)
#> Loading required package: xml2
library(magrittr)
teams= c("miami-marlins", "cleveland-indians")

tables <- list()
index <- 1
for(i in teams){
  url <- paste0("https://www.covers.com/sport/baseball/mlb/teams/main/",(i),"/2019")
  table <- url %>% 
    read_html() %>% 
    html_nodes("table")%>%
    .[[12]]%>%
    html_table()
  
  tables[index] <- table
  
  index <- index + 1
  
  
}
#> Warning in tables[index] <- table: number of items to replace is not a multiple
#> of replacement length

#> Warning in tables[index] <- table: number of items to replace is not a multiple
#> of replacement length
df <- do.call("rbind", tables)

reprex 包(v0.3.0) 于 2020 年 10 月 15 日创建,当我运行代码时,我收到上述警告消息,并且代码仅获取两支球队进行比赛的日期。 我主要从尝试使用 rvest 循环一个命令来从多个页面中抓取表格的帖子中借用了代码,然后尝试稍微调整它以适应我需要的内容,但显然我的改动已经把它搞砸了。 下面我发布了我编写的代码,用于从运行良好的各个网站上抓取表格。

url15 <- paste0("https://www.covers.com/sport/baseball/mlb/teams/main/miami-marlins/2019")
table <- url15 %>% 
  read_html() %>% 
  html_nodes("table")%>%
  .[[12]]%>%
  html_table()
#> Error in url15 %>% read_html() %>% html_nodes("table") %>% .[[12]] %>% : could not find function "%>%"

reprex 包(v0.3.0) 于 2020 年 10 月 15 日创建

如果有人能指出我在这里做错了什么,并在可能的情况下用外行的术语解释它,我将不胜感激,因为我对此很陌生。

尝试这个

library(rvest)
library(dplyr)
teams <- c("miami-marlins", "cleveland-indians")
dplyr::bind_rows(lapply(
  paste0("https://www.covers.com/sport/baseball/mlb/teams/main/", teams, "/2019"), 
  . %>% read_html() %>% html_nodes("table") %>% .[[12]] %>% html_table() %>% {`names<-`(.[-1L, ], .[1L, , drop = TRUE])}
))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM