gpt4 book ai didi

r - XPath。获取标签内的文本,而不是标签外的其他文本

转载 作者:行者123 更新时间:2023-12-03 17:12:00 27 4
gpt4 key购买 nike

我在html页面中有两种模式,它们之间的唯一区别是在封闭的strong标签之后存在附加文本。这是一个例子:

示例1(在标记strong之后的其他文本):

<p><strong>14h45 De violents combats ont lieu à Zawiyah</strong>, à 40km à l'Ouest de Tripoli entre les insurgés et les forces restées fidèles au colonel Kadhafi. Un témoin oculaire, cité par l'agence de presse italienne Ansa, affirme: "C'est un massacre, il est difficile d'estimer le nombre de morts". Il y aurait une centaine de victimes, selon la BBC. &nbsp;</p>


示例2(无其他文本):

<p><strong>Quitte à revenir dans l'euro quelques années plus tard?</strong>&nbsp;</p>


我需要两个XPath,以便在两种情况下都可以在标签' ... '中获得文本。

现在我正在使用

'//p//strong//text()[normalize-space()]' 


但是当我需要两个单独的XPath时,它会从两个示例中捕获文本。

任何帮助表示赞赏。

UPD
还有一种处理案件的方法

<p>
<a href="http://www.slate.com/id/2286172/" target="_blank">
<strong>Combien coûte un mercenaire?</strong>
</a>
Alors que le régime de Kadhafi semble avoir recours à des combattants étrangers pour réprimer les insurgés, Slate se penche sur leur fonctionnement... et leur émoluement (en anglais).&nbsp;
</p>


XPath

"//p//strong[not(following-sibling::text()[normalize-space()])]//text()"


将返回:

Combien coûte un mercenaire?


但是标签后面有一个文本

最佳答案

您可以在谓词中为following-sibling::text()[normalize-space()]使用strong来仅获取strong元素,后跟非空文本节点:

//p/strong[following-sibling::text()[normalize-space()]]/text()


并使用相反的谓词 not(following-sibling::text()[normalize-space()])来获取其余的 strong元素:

//p/strong[not(following-sibling::text()[normalize-space()])]/text()


注意:假设 &nbsp;在您使用的XPath库中被视为空白,以上内容将起作用。否则,您可能需要将 strong元素后面的文本节点的长度与文本 &nbsp;的长度进行比较,以确定该文本节点是否不仅仅是空白( &nbsp;),例如:

following-sibling::text()[string-length(normalize-space())>string-length('&nbsp;')]

关于r - XPath。获取标签内的文本,而不是标签外的其他文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34021609/

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