gpt4 book ai didi

python - 在 python 中使用 xpath 查询从具有子节点的以下节点中选择整个文本

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:38 25 4
gpt4 key购买 nike

我想在 python 中使用 XPath 提取 a 标记 的以下节点的内容。到目前为止,我设法提取了其中没有内部标签的内容。问题是,如果以下节点中有子节点,我的方法将不起作用。我正在使用 lxml 包,这是我的代码:

from lxml.html import etree, fromstring

reference_titles = root.xpath("//table[@id='vulnrefstable']/tr/td")
for tree in reference_titles:
a_tag = tree.xpath('a/@href')[0]
title = tree.xpath('a/following-sibling::text()')

这适用于此 html:

<tr>

<td class="r_average">

<a href="http://somelink.com" target="_blank" title="External url">
http://somelink.com
</a>
<br/> SECUNIA 27633
</td>

</tr>

这里的标题是正确的“SECUNIA 27633”,但在这个 html 中:

<tr>

<td class="r_average">

<a href="http://somelink.com" target="_blank" title="External url">
http://somelink.com
</a>
<br/> SECUNIA 27633 <i>Release Date:</i> tomorrow
</td>

</tr>

结果是“SECUNIA 27633 tomorrow

如何提取“SECUNIA 27633 发布日期:明天”?


编辑:XPath 中使用 node() 而不是 text() 返回其中的所有节点.所以我使用它并使用嵌套的 for 语句创建最终字符串

title = tree.xpath('a/following-sibling::node()')

但我想知道是否有更好的方法来简单地提取文本内容,而不管使用 XPath 查询的子节点

最佳答案

试试这个:

for tree in reference_titles:
a_tag = tree.xpath('a/@href')[0]
title = " ".join([node.strip() for node in tree.xpath('.//text()[not(parent::a)]') if node.strip()])

关于python - 在 python 中使用 xpath 查询从具有子节点的以下节点中选择整个文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51196089/

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