如何使用 rvest 在 R 中提取维基百科 table 的特定元素?

How can I extract a particular element of Wikipedia table in R using rvest?

例如,对于 NYC,我想从信息框(右侧的 table)中提取网站。

我正在使用这个:

url = "https://en.wikipedia.org/wiki/New_York_City"
page = read_html(url)

links = page %>%
  html_nodes("table tr a") 

但这是错误的。

使用 xpath 您可以首先通过其 class 名称 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>
...