我已经回顾了几个类似问题的答案,这些问题都与这个相似的主题有关,但似乎都不适合我。
(loop across multiple urls in r with rvest)
(Harvest (rvest) multiple HTML pages from a list of urls)
我有一个URL列表,我希望从每个URL中获取该表,并将其附加到主数据框架中。
## get all urls into one list
page<- (0:2)
urls <- list()
for (i in 1:length(page)) {
url<- paste0("https://www.mlssoccer.com/stats/season?page=",page[i])
urls[[i]] <- url
}
### loop over the urls and get the table from each page
table<- data.frame()
for (j in urls) {
tbl<- urls[j] %>%
read_html() %>%
html_node("table") %>%
html_table()
table[[j]] <- tbl
}第一部分以expect的方式工作,并获取我想要抓取的urls列表。我得到以下错误:
Error in UseMethod("read_xml") :
no applicable method for 'read_xml' applied to an object of class "list"对于如何纠正这个错误并将3个表环成一个DF,有什么建议吗?我很感激你的任何建议。
发布于 2018-12-08 17:13:28
试试这个:
library(tidyverse)
library(rvest)
page<- (0:2)
urls <- list()
for (i in 1:length(page)) {
url<- paste0("https://www.mlssoccer.com/stats/season?page=",page[i])
urls[[i]] <- url
}
### loop over the urls and get the table from each page
tbl <- list()
j <- 1
for (j in seq_along(urls)) {
tbl[[j]] <- urls[[j]] %>% # tbl[[j]] assigns each table from your urls as an element in the tbl list
read_html() %>%
html_node("table") %>%
html_table()
j <- j+1 # j <- j+1 iterates over each url in turn and assigns the table from the second url as an element of tbl list, [[2]] in this case
}
#convert list to data frame
tbl <- do.call(rbind, tbl)在原始代码中for循环末尾的table[[j]] <- tbl是不必要的,因为我们在这里将每个url分配为tbl列表的一个元素:tbl[[j]] <- urls[[j]]
发布于 2018-12-08 04:02:57
这是你的问题:
for (j in urls) {
tbl<- urls[j] %>% 使用j in urls时,j值不是整数,而是urls本身。
尝试:
for (j in 1:length(urls)) {
tbl<- urls[[j]] %>%
read_html() %>%
html_node("table") %>%
html_table()
table[[j]] <- tbl
}您也可以使用seq_along()
for (j in seq_along(urls))https://stackoverflow.com/questions/53679009
复制相似问题