加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:59:17 所属栏目:百科 来源:网络整理
导读:我使用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(在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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读