【问题标题】:Rvest web scraping gives open.connection errorRvest 网页抓取给出了 open.connection 错误
【发布时间】:2018-12-01 05:39:07
【问题描述】:

我正在尝试遍历 ID 列表以从 Fangraphs 中删除一些表格。以下代码在我插入单个 id 并删除 for 循环时有效,但在我重新插入 for 循环时给出错误(即 open.connection(x, "rb") 中的错误:HTTP 错误 400。)。我环顾了各个地方,包括herehere,但我尝试的任何方法似乎都不起作用。我还将原来的 1000 多个 ID 列表缩短到只有 10 个,但仍然收到错误消息。

有人可以帮忙吗?感觉这应该是一个非常简单的抓取任务,因为除了 ID 和页面布局非常简单,url 完全相同。提前非常感谢。

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
}

【问题讨论】:

  • 您可以尝试使用paste0 在连接您的网址时设置一个空的分隔符。我不确定带空格的网址是否可以使用。如果不是这样:您能否提供可复制的 ID 列表?

标签: r for-loop web-scraping rvest


【解决方案1】:

看来我解决了问题。也许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
  }
}

【讨论】:

    猜你喜欢
    • 2023-01-07
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2020-07-18
    • 2019-02-17
    • 1970-01-01
    相关资源
    最近更新 更多