gpt4 book ai didi

html - 如何用 XPath 中的 XML 值识别节点?

转载 作者:行者123 更新时间:2023-11-27 23:27:54 25 4
gpt4 key购买 nike

我使用 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”的 span。并获取节点,以提取“额外数字”?
    我知道如何使用 xpathApply 识别节点以获取 xmlValue 或某些属性(如 hrefxmlGetAttr)。但是我不知道如何在知道节点的 xml 值的情况下识别节点。

      xpathApply(page, '//span[@class="property"]',xmlValue)
  • 如果我想获取属性类“Surface”的“值”72,最有效的方法是什么?

这是我开始做的:首先,我提取所有“属性”:

xpathApply(page, '//span[@class="property"]',xmlValue)

然后我提取所有“值”:

xpathApply(page, '//span[@class="value"]',xmlValue)

然后我构建一个列表或矩阵,这样我就可以识别“Surface”的值,即 72。但问题是,有时,class="property" 的跨度不能在 h2 中有一个带有 class="value"的跨度。所以我无法建立一个合适的列表。

这会是最有效的方法吗?用class="property"识别span,然后识别包含这个spanh2,然后识别span 使用 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

根据要求。

关于html - 如何用 XPath 中的 XML 值识别节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37513226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com