【发布时间】:2019-05-24 15:58:15
【问题描述】:
我一直在尝试抓取 mlb 交易页面 (http://mlb.mlb.com/mlb/transactions/index.jsp#month=5&year=2019) 以获取每个给定交易的相应日期和文本,但没有成功。使用 rvest 和选择器小工具,我编写了一个简短的函数,它应该给我显示从第一个可用 n 2001 到 2019 年 3 月的表格。
我只是收到这一系列错误,但什么也没有发生。
这是我从给定网站上抓取数据的代码。
library(tidyverse)
library(rvest)
# breaking the URL into the start and end for easy pasting to fit timespan
url_start = "http://mlb.mlb.com/mlb/transactions/index.jsp#month="
url_end = "&year="
# function which scrapes data
mlb_transactions = function(month, year){
url = paste0(url_start, month, url_end, year)
payload = read_html(url) %>%
html_nodes("td") %>%
html_table() %>%
as.data.frame()
payload
}
# function run on appropriate dates
mlb_transactions(month = 1:12, year = 2001:2019)
这是我遇到的错误
Show Traceback
Rerun with Debug
Error in doc_parse_file(con, encoding = encoding, as_html = as_html, options = options) :
Expecting a single string value: [type=character; extent=19].
这里是追溯
12.
stop(structure(list(message = "Expecting a single string value: [type=character; extent=19].",
call = doc_parse_file(con, encoding = encoding, as_html = as_html,
options = options), cppstack = NULL), class = c("Rcpp::not_compatible",
"C++Error", "error", "condition")))
11.
doc_parse_file(con, encoding = encoding, as_html = as_html, options = options)
10.
read_xml.character(x, encoding = encoding, ..., as_html = TRUE,
options = options)
9.
read_xml(x, encoding = encoding, ..., as_html = TRUE, options = options)
8.
withCallingHandlers(expr, warning = function(w) invokeRestart("muffleWarning"))
7.
suppressWarnings(read_xml(x, encoding = encoding, ..., as_html = TRUE,
options = options))
6.
read_html.default(url)
5.
read_html(url)
4.
eval(lhs, parent, parent)
3.
eval(lhs, parent, parent)
2.
read_html(url) %>% html_nodes("td") %>% html_table() %>% as.data.frame()
1.
mlb_transactions(month = 1:12, year = 2001:2019)
最后一点是,我的计划是,虽然我还不知道该怎么做,因为在交易表上,并不是每笔交易都有一个直接离开的日期,但有一个隐含的日期跨度,我可以这样做吗加载后,每个空的日期列都会在其上方填充列的信息(如果已填充),这会运行一种循环,还是有更好的方法从一开始就加载日期?
【问题讨论】:
-
这里有几个问题。用两个向量调用函数不是嵌套循环。在函数中添加 'print(url)' 以查看结果。
read_html()也被设计为接受单个 url 而不是 URL 的向量。 -
@Dave2e 我是否必须将其修改为 for 循环?喜欢(2001 年:2019 年)..等?
-
是的,这是直截了当的方式。我还建议阅读网站上的服务条款,以确保您没有违反。另外,我会在调用
read_html之间添加 1 秒的暂停,这样就不会像拒绝服务攻击一样。
标签: r function dataframe web-scraping rvest