我使用R来抓取网站,并且在解析HTML代码时,我的代码如下:
<div class="line">
<h2 class="clearfix">
<span class="property">Number<div>number extra</div></span>
<span class="value">3</span>
</h2>
</div>
<div class="line">
<h2 class="clearfix">
<span class="property">Surface</span>
<span class="value">72</span>
</h2>
</div>
现在,我想在此代码中获取一些值。
如何用xml值“ Number”标识范围。并获取节点,以提取“额外数量”?我知道如何使用xpathApply来标识节点,以获取xmlValue或某些属性(例如href
与xmlGetAttr
)。但是我不知道如何通过知道其xmlvalue来识别节点。
xpathApply(page, '//span[@class="property"]',xmlValue)
如果我想获取属性类“ Surface”的“值” 72,最有效的方法是什么?
这是我开始做的事情:首先,我提取所有“属性”:
xpathApply(page, '//span[@class="property"]',xmlValue)
然后我提取所有“值”:
xpathApply(page, '//span[@class="value"]',xmlValue)
然后,我建立一个列表或矩阵,以便可以标识“ Surface”的值,即72。但是问题是,有时,带有的跨度class="property"
不能具有紧随其后的class =“ value”的跨度一个h2
。因此,我无法建立适当的列表。
这可能是最有效的方法吗?:标识范围with class="property"
,然后标识h2
包含此范围的对象span
,然后标识span
with class="value"
?
要通过添加单个根元素使HTML格式正确,
<?xml version="1.0" encoding="UTF-8"?>
<r>
<div class="line">
<h2 class="clearfix">
<span class="property">Number
<div>number extra</div>
</span>
<span class="value">3</span>
</h2>
</div>
<div class="line">
<h2 class="clearfix">
<span class="property">Surface</span>
<span class="value">72</span>
</h2>
</div>
</r>
(A)这个XPath表达式,
//span[@class='property' and starts-with(., 'Number')]/div/text()
将返回
number extra
按照要求。
(B)这个XPath表达式,
//h2[span[@class='property' and . = 'Surface']]/span[@class='value']/text()
将返回
72
按照要求。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句