【发布时间】:2020-04-12 03:19:18
【问题描述】:
在收到 Montgomery Clift 在另一篇文章中的回答后(请参阅 here),我尝试编写一个函数,以便在一个月的跨度内循环多天以从棒球章程(示例页面 here)中收集数据。该代码成功下载了每天的文件,但随后我收到以下错误:
Error in list_to_dataframe(res, attr(.data, "split_labels"), .id,
id_as_factor) : Results must be all atomic, or all data frames
函数代码后面是我正在运行的尝试收集所有数据的代码:
fetch_adjusted <- function(day) {
fname <- paste0(“standings201909”, day, “.html”)
download.file(url =
paste0(“https://legacy.baseballprospectus.com/standings/index.php?
odate=2019-09-“, day), destfile=fname)
doc0 <- htmlParse(file=fname, encoding=“UTF-8”)
doc1 <- xmlRoot(doc0)
doc2 <- getNodeSet(doc1, “//table[@id=‘content’]”)
standings <- readHTMLTable(doc2[[1]], header=TRUE, skip.rows=1,
stringsAsFactors=FALSE)
standings <- standings[[1]]
standings$day <- day
standings
}
Sept <- ldply(1:29, fetch_adjusted, .progress="text")
谁能帮助弄清楚如何调整我当前的代码,以避免任何错误?谢谢!
更新:
我现在可以通过以下方式成功下载跨度内多个日期的 xls 文件:
dates <- seq(as.Date("2019-09-01"), as.Date("2019-09-30"), by=1)
fetch_adjusted <- function(dates) {
url <-
paste0("https://legacy.baseballprospectus.com/standings/index.php?
odate=", dates, "&otype=xls")
destfile <- "test.xls"
download.file(url, destfile, mode = "wb")
}
但是现在,无论我使用什么模式(“w”、“wb”、“a”),它都不会附加文件,所以我最终得到的只是最后一个文件(在这种情况下,2019-09 -30),这是一个空的电子表格。我的想法是它只是每次都用最新的文件覆盖最后一个文件。有解决办法吗?
【问题讨论】:
-
我从您的问题中删除了标签
PHP,因为它似乎完全不相关 -
问题在于这一行
download.file(url, destfile, mode = "wb")您正在覆盖同一个文件。您可以将变量添加到destfile以使其唯一。您最终会得到许多文件。然后,您可以编写不同的函数来读取每个文件并将其附加到单个文件中。
标签: r function web-scraping xls