Rvest - UseMethod("read_xml") 中的错误:没有适用于“read_xml”的方法应用于“factor”类的对象

Pet*_*goe 1 r rvest

我正在使用以下 rvest 代码:

library(rvest)

URL <- "http://www.soccerstats.com/matches.asp" #Feed page

WS <- read_html (URL) #reads webpage into WS variable

URLs <- WS %>% html_nodes ("a:nth-child(1)") %>% html_attr("href")         %>% as.character() # Get the CSS nodes & extract the URLs 

URLs <- paste0("http://www.soccerstats.com/",URLs) 

grepl("pmatch", oversdf$URLs)

URLs <-subset(oversdf, grepl("pmatch", oversdf$URLs),stringsAsFactors       =       FALSE)

Catcher1 <- data.frame(FMatch=character(),TotalGoals=character    (),stringsAsFactors = FALSE)

#Start of for loop

for (i in URLs) {

WS1 <- read_html(i)
FMatch <- WS1 %>% html_nodes("H1") %>% html_text() %>% as.character()
TotalGoals <- WS1 %>% html_nodes(".trow3+ .trow2 td~ td+ td font b") %>%     html_text() %>% as.character()
temp <- data.frame(FMatch,TotalGoals)
Catcher1 <- rbind(Catcher1,temp)
cat("*")

}
Run Code Online (Sandbox Code Playgroud)

当它尝试运行循环时,我收到错误消息:

UseMethod("read_xml") 中的错误:没有适用于“read_xml”的方法应用于“factor”类的对象

查看论坛帖子,我需要使用 stringsAsFactors = FALSE,因为我的数据框将字段数据存储为因子而不是字符串。

我认为它剩下的唯一地方是在临时 df 上:

temp <- data.frame(FMatch,TotalGoals)

但是我尝试将它应用于上述 df it 语法错误,有什么想法吗?

(显然我是这个新手,所以我可能错了上面是什么导致了错误,看起来它来自我读过的各种论坛帖子)

干杯

Ste*_*edy 5

基本上问题在于在每个循环中设置 HTML 环境。为了解决这个问题,我html_session()在每个循环开始时使用并将其提供给html_nodes()

for (i in URLs) {

  WS1 <- html_session(i)
  FMatch <- html_nodes(WS1, "h1") %>% html_text() %>% as.character()
  TotalGoals <- html_nodes(WS1, ".trow3+ .trow2 td~ td+ td font b") %>% html_text() %>% as.character()
  temp <- data.frame(FMatch,TotalGoals)
  Catcher1 <- rbind(Catcher1,temp)
  cat("*")
}
Run Code Online (Sandbox Code Playgroud)

返回:

R> Catcher1
                       FMatch TotalGoals
1      Santa Cruz vs Criciuma       2.07
2         FC Kiffen vs FC KTP       3.08
3       Furth B vs Augsburg B       2.00
4          Vikingur R. vs IBV       3.67
5  IA Akranes vs KR Reykjavik       4.00
6      Hafnarfjordur vs Valur       2.84
7        Valerenga B vs Skeid       2.25
8      Constanta vs Voluntari       1.75
9         Syrianska vs Norrby       3.46
10          Osters IF vs GAIS       3.14
11 Sleipner vs Linkoping City       2.94
Run Code Online (Sandbox Code Playgroud)