r语言 - 使用 rvest 从 HTML 表中提取超链接



我在这里看到了类似的问题并实施了解决方案,但似乎仍然无法弄清楚这个问题。仍然是一个R新手,所以请耐心等待:我已经设法使用rvest从这个网站上获得了巴拉克奥巴马的演讲表:

library(rvest)
page <- read_html("http://www.americanrhetoric.com/barackobamaspeeches.htm")
speeches <- page %>%
  html_nodes(xpath = '//*[@id="AutoNumber1"]') %>% 
  html_table(fill=TRUE)
speeches <- speeches[[1]][,2:4]
head(speeches)

这会产生:

            X2                                            X3    X4
1             <NA>                                          <NA>  <NA>
2    Delivery Date                  Speech Title/Text/MultiMedia Audio
3     27 July 2004 Democratic National Convention Keynote Speech   mp3
4  06 January 2005 Senate Speech on Ohio Electoral Vote Counting   mp3
5     04 June 2005              Knox College Commencement Speech   mp3
6 15 December 2005              Senate Speech on the PATRIOT Act   mp3

但是,我还想提取"语音"列中每个条目的超链接,该超链接自然存在于href属性中。我已经在网上对此进行了非常彻底的研究,有些人说也用 html_attr('href') 指定 html 属性,但是如果我将其包含在上面的代码中,我会收到此错误:

Error in UseMethod("xml_attr") : no applicable method for 'xml_attr' applied to an object of class "list"

另一个人建议用trace修改实际功能,但这似乎过于复杂,因为看起来很简单。知道我在哪里绊倒吗?

使用选择器小工具确定节点,我提取了 URL:

page %>% html_nodes("td:nth-child(2) a") %>% html_attr("href")

最新更新