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

Tom*_*Tom 7 xml xpath r

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

首先,相关的XML片段:

 <div class="offer-name">
        <a href="http://www.somesite.com" itemprop="name">Fancy Product</a>
      </div>
Run Code Online (Sandbox Code Playgroud)

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

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

这需要一些时间(我是一个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, "//div[@class='offer-name']", xmlValue) 
Run Code Online (Sandbox Code Playgroud)

jdh*_*son 14

href是一个属性.您可以选择适当的节点//div/a并使用以下xmlGetAttr功能name = href:

'<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, "//div[@class='offer-name']", xmlValue) 
hrefs <- xpathSApply(parsedHTML, "//div/a", xmlGetAttr, 'href')
> hrefs
[1] "http://www.somesite.com"
Run Code Online (Sandbox Code Playgroud)


jlh*_*ard 5

您也可以使用XPath直接执行此操作,而无需使用xpathSApply(...).

xData <- '<div class="offer-name">
  <a href="http://www.somesite.com" itemprop="name">Fancy Product</a>
  </div>'
library(XML)
parsedHTML <- xmlParse(xData)
hrefs <- unlist(parsedHTML["//div[@class='offer-name']/a/@href"])
hrefs
#                      href 
# "http://www.somesite.com" 
Run Code Online (Sandbox Code Playgroud)