1

我尝试从网站上提取一些信息

library(rvest)
library(XML)
url <- "http://wiadomosci.onet.pl/wybory-prezydenckie/xcnpc"
html <- html(url)

nodes <- html_nodes(html, ".listItemSolr") 
nodes

我得到了 30 部分 HTML 代码的“列表”。我想从“列表”的每个元素中提取最后一个 href 属性,所以对于 30. 元素它将是

<a href="http://wiadomosci.onet.pl/kraj/w-sobote-prezentacja-hasla-i-programu-wyborczego-komorowskiego/tvgcq" title="W sobotę prezentacja hasła i programu wyborczego Komorowskiego">

所以我想得到字符串

"http://wiadomosci.onet.pl/kraj/w-sobote-prezentacja-hasla-i-programu-wyborczego-komorowskiego/tvgcq"

问题是html_attr(nodes, "href")不起作用(我得到了 NA 的向量)。所以我想到了正则表达式,但问题是那nodes不是字符列表。

class(nodes)
[1] "XMLNodeSet"

我试过了

xmlToList(nodes)

但它也不起作用。

所以我的问题是:如何使用为 HTML 创建的一些函数来提取这个 url?或者,如果不可能将 XMLNodeSet 转换为字符列表?

4

2 回答 2

8

Try searching inside nodes' children:

nodes <- html_nodes(html, ".listItemSolr") 

sapply(html_children(nodes), function(x){
  html_attr( x$a, "href")
})

Update

Hadley suggested using elegant pipes:

html %>%  
  html_nodes(".listItemSolr") %>% 
  html_nodes(xpath = "./a") %>% 
  html_attr("href")
于 2015-03-13T22:21:43.333 回答
2

封装 XML 函数getHTMLLinks()几乎可以为我们完成所有工作,我们只需要编写 xpath 查询。这里我们查询所有节点属性以确定是否有包含“listItemSolr”,然后选择父节点进行href查询。

getHTMLLinks(url, xpQuery = "//@*[contains(., 'listItemSolr')]/../a/@href")

xpQuery我们正在执行以下操作:

  • //@*[contains(., 'listItemSolr')]查询listItemSolr的所有节点属性
  • /..选择父节点
  • /a/@href获取href链接
于 2015-03-14T16:26:23.363 回答