【发布时间】:2016-08-06 19:28:10
【问题描述】:
我感兴趣的表是纽约市米其林星级餐厅的维基百科表,获得的星数以图片表示。
我能够使用两个步骤来抓取表格(首先获取“Name”和“Borough”列中的单词,然后获取表格正文中的 alt 标签),但我想知道是否可以完成一步。我能够使用 rvest 包抓取数据。
由于 XML::readHTMLTable 函数无法读取维基百科页面,我尝试了 htmltab 包但没有成功,因为我无法确定 bodyFun 参数所需的函数。说实话,我是网络抓取...和功能的新手。
我参考的问题:
Scraping html table with images using XML R package
Scraping html tables into R data frames using the XML package
这是我的代码:
library(stringr)
library(rvest)
library(data.table)
url <- "http://en.wikipedia.org/wiki/List_of_Michelin_starred_restaurants_in_New_York_City"
#Scrape the first two columns, restaurant name and borough
name.boro <- url %>% read_html() %>% html_nodes("table") %>% html_table(fill = TRUE)
name.boro <- as.data.table(name.boro[[1]])
name.boro[, 3:length(name.boro) := NULL]
135 * 13 #1,755 cells in first table
#scrape tables for img alt
#note that because I used the "td" node, entries for all cells in all tables were pulled
stars <- url %>% read_html() %>% html_nodes("td") %>% html_node("img") %>% html_attr("alt")
stars
#Make vector of numbers to index each column
df <- vector("list", 13)
for (i in 1:13){
df[[i]] <- seq(i, 1755, 13)
}
#Put everything together
Mich.Guide <- name.boro
Mich.Guide[, c("X2006", "X2007", "X2008", "X2009", "X2010", "X2011", "X2012", "X2013", "X2014", "X2015",
"X2016") := .(stars[unlist(df[3])], stars[unlist(df[4])], stars[unlist(df[5])],
stars[unlist(df[6])], stars[unlist(df[7])], stars[unlist(df[8])],
stars[unlist(df[9])], stars[unlist(df[10])], stars[unlist(df[11])],
stars[unlist(df[12])], stars[unlist(df[13])] )]
谢谢!
【问题讨论】:
-
“由于 XML 包无法读取维基百科页面……” => 请解释一下这个误会。
-
下面抛出了一个错误:
url <- "http://en.wikipedia.org/wiki/List_of_Michelin_starred_restaurants_in_New_York_City"readHTMLTable(url, which=1)...所以我在这里查看了http://stackoverflow.com/questions/7407735/importing-wikipedia-tables-in-r,用户 Shambho 评论说安全连接在包中不起作用。您可以在该站点上使用 readHTMLTable 命令吗? -
说
readHTMLTable()不起作用 == “不能使用 XML 包”有点虚伪 -
该功能在其他网站上运行良好,所以我不能说它“不起作用”。在
readHTMLTablewikipedia 的软件包文档中,使用了注释作为示例,从去年开始不支持安全连接。不管怎样,我在编辑中使语言更加清晰。 -
除了
RCurl和stringi之外,仅使用基本R 将XML解决方案添加到我的答案中。
标签: html r web-scraping rvest