Rvest网站抓取会产生open.connection错误

时间:2018-06-21 19:22:34

标签: r for-loop web-scraping rvest

我正在尝试遍历ID列表,以从Fangraphs上刮一些表。当我插入一个ID并删除for循环时,以下代码可以工作,但是当我重新插入for循环时,会出现错误(即open.connection(x,“ rb”)中的错误:HTTP错误400。)。我到处逛过herehere等各个地方,但似乎没有任何尝试。我还将原来的1000个以上ID的列表缩短到了10个,但仍然收到错误消息。

有人可以帮忙吗?假设url与ID完全一样,并且页面布局非常简单,这应该是一个非常简单的抓取任务。提前非常感谢。

for (id in pitchIDs$playerid) {
    url <- paste("https://www.fangraphs.com/statsd.aspx? 
playerid=",id,"&position=P&type=&gds=&gde=&season=all")
    gamelogs <- url %>%
    read_html() %>%
    html_nodes(xpath = '//*[@id="DailyStats1_dgSeason1_ctl00"]') %>%
    html_table()
    gamelogs$id <- id
}

1 个答案:

答案 0 :(得分:0)

好像我解决了这个问题。也许paste0帮了大忙。谢谢@cderv。参见下面的代码...

data = c()
for(id in pitchIDs$playerid) {
  url <- read_html(paste0("https://www.fangraphs.com/statsd.aspx? 
         playerid=",id,"&position=P&type=&gds=&gde=&season=all"))
  gamelogs <- url %>%
  html_nodes(xpath = '//*[@id="DailyStats1_dgSeason1_ctl00"]') %>%
  html_table()
  gamelogs <- gamelogs[[1]]
  gamelogs$id <- id
if(is.data.frame(data)) {
  names(gamelogs) = names(data)
  data = rbind(data, gamelogs)
  } else {
    data = gamelogs
  }
}