如何使用rvest在R中提取维基百科表中的特定元素?
问题描述:
例如,对于NYC我想从信息框中提取网站(右表)。如何使用rvest在R中提取维基百科表中的特定元素?
我使用这个:
url = "https://en.wikipedia.org/wiki/New_York_City"
page = read_html(url)
links = page %>%
html_nodes("table tr a")
但是,这是错误的。
答
使用xpath
您可以先以类名称infobox
获取信息框,然后通过其标记名称a
获取所有链接。
library("rvest")
url <- "https://en.wikipedia.org/wiki/New_York_City"
infobox <- url %>%
read_html() %>%
html_nodes(xpath='//table[contains(@class, "infobox")]//a')
print(infobox)
输出
{xml_nodeset (81)} [1] <a href="/wiki/City_(New_York)" class="mw-redirect" title="City (New York)">City</a> [2] <a href="/wiki/File:NYC_Montage_2014_4_-_Jleon.jpg" class="image" title="Clockwise, from top: Midtow ... [3] <a href="/wiki/Midtown_Manhattan" title="Midtown Manhattan">Midtown Manhattan</a> [4] <a href="/wiki/Times_Square" title="Times Square">Times Square</a> [5] <a href="/wiki/Unisphere" title="Unisphere">Unisphere</a> ...
DONE。对不起。 – Petr
考虑发布答案或删除问题。 – hrbrmstr