使用xpathSApply来刮取R中的XML属性

我使用xpathSApply(在XML包中)在R中搜索XML并且无法将属性拉出来.

首先,相关的XML片段:

<div class="offer-name">
        <a href="http://www.somesite.com" itemprop="name">Fancy Product</a>
      </div>

我使用以下方法成功地拉出了’Fancy Product'(即元素?)

Products <- xpathSApply(parsedHTML,"//div[@class='offer-name']",xmlValue)

这花了一些时间(我是一个n00b),但文档很好,我可以利用这里有几个已回答的问题.我无法弄清楚如何拉出“http://www.somesite.com”(属性?).我推测它涉及将第三个术语从’xmlValue’更改为’xmlGetAttr’,但我可能完全没有了.

仅供参考(1)还有2个父母< DIV>在我粘贴的片段上面,(2)这里是缩写的完整代码(我认为不相关,但为了完整性而包括在内)是:

library(XML)
library(httr)

content2 = paste(readLines(file.choose()),collapse = "\n") # User will select file.
parsedHTML = htmlParse(content2,asText=TRUE)

Products <- xpathSApply(parsedHTML,xmlValue)
href是一个属性.您可以选择适当的节点// div / a并使用名称= href的xmlGetAttr函数
'<div class="offer-name">
  <a href="http://www.somesite.com" itemprop="name">Fancy Product</a>
  </div>' -> xData
library(XML)
parsedHTML <- xmlParse(xData)
Products <- xpathSApply(parsedHTML,xmlValue) 
hrefs <- xpathSApply(parsedHTML,"//div/a",xmlGetAttr,'href')
> hrefs
[1] "http://www.somesite.com"

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念