我建立了一个简单的scrape来获取一个包含2020年NFL选秀结果的数据框架。我打算用这段代码来映射几年的结果,但由于某些原因,当我改变了2020年以外的任何其他年份的单页scrape代码,我在底部得到了错误。
library(tidyverse)
library(rvest)
library(httr)
library(curl)
这个2020年的搜刮工作完美无瑕,虽然col名称在第1行,这对我来说不是什么大问题,因为我可以在以后处理这个问题(虽然提到,以防这可能与这个问题有关)。
x <- "https://www.pro-football-reference.com/years/2020/draft.htm"
df <- read_html(curl(x, handle = curl::new_handle("useragent" = "Mozilla/5.0"))) %>%
html_nodes("table") %>%
html_table() %>%
as.data.frame()
下面的url由2020改为2019,这是一个活动页面,表格格式相同。不知道为什么,和上面一样的调用不能用。
x <- "https://www.pro-football-reference.com/years/2019/draft.htm"
df <- read_html(curl(x, handle = curl::new_handle("useragent" = "Mozilla/5.0"))) %>%
html_nodes("table") %>%
html_table() %>%
as.data.frame()
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, :
arguments imply differing number of rows: 261, 2
有两个表在提供的网址。有核心的草案(表1。id = "drafts"
)和补充草案(表2。id = "drafts_supp"
).
该 as.data.frame()
调用失败的原因是,它正试图将两个表合并,但它们的名称和数字列都不同。你可以直接 rvest
读取您感兴趣的特定表格,只需提供 html_node()
与 xpath
或 selector
. 你可以找到 xpath
或 selector
通过检查你感兴趣的特定表,右击>在ChromeMozilla上检查。请注意,如果选择器要使用id,你需要使用 #drafts
不只是 drafts
而对于xpath来说,你通常需要用单引号来包裹文本。
html_node(xpath = '//*[@id="drafts"]')
html_node(xpath = "//*[@id="drafts"]")
注意,我相信 html_nodes("table")
您的例子中使用的是不必要的,因为 html_table()
已经只选择了表格。
x <- "https://www.pro-football-reference.com/years/2019/draft.htm"
raw_html <- read_html(x)
# use xpath
raw_html %>%
html_node(xpath = '//*[@id="drafts"]') %>%
html_table()
# use selector
raw_html %>%
html_node("#drafts") %>%
html_table()