【发布时间】:2019-08-18 22:48:54
【问题描述】:
我正在尝试使用rvest 学习网络抓取,并尝试重现此处给出的示例:
https://www.r-bloggers.com/using-rvest-to-scrape-an-html-table/
安装了rvest后,我只是复制粘贴了文章中给出的代码:
library("rvest")
url <- "http://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population"
population <- url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[1]') %>%
html_table()
population <- population[[1]]
唯一的区别是我使用read_html() 而不是html(),因为后者已被弃用。
与文章中报告的输出不同,这段代码产生了熟悉的:
Error in population[[1]] : subscript out of bounds
其起源是在没有最后两行的情况下运行代码给population一个值{xml_nodeset (0)}
之前所有关于此的问题都表明这是由于表格在 javascript 中动态格式化造成的。但这里的情况并非如此(除非 Wikipedia 自 2015 年 rbloggers 文章以来已更改其格式)。
任何见解都将不胜感激,因为我不知所措!
【问题讨论】:
标签: html r web-scraping rvest