gpt4 book ai didi

python - xpath

里面

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:39 25 4
gpt4 key购买 nike

我开始在 python3 中使用 xpath 并面临这种行为。这对我来说似乎是错误的。为什么它匹配 span-text,而不匹配 h3 中的 p-text?

>>> from lxml import etree

>>> result = "<h3><p>Hallo</p></h3>"
>>> tree = etree.HTML(result)
>>> r = tree.xpath('//h3//text()')
>>> print(r)
[]

>>> result = "<h3><span>Hallo</span></h3>"
>>> tree = etree.HTML(result)
>>> r = tree.xpath('//h3//text()')
>>> print(r)
['Hallo']

非常感谢!

最佳答案

您的第一个 XPath 正确地没有返回任何结果,因为 <h3>在相应的tree不包含任何文本节点。您可以使用 tostring()查看树的实际内容的方法:

>>> result = "<h3><p>Hallo</p></h3>"
>>> tree = etree.HTML(result)
>>> etree.tostring(tree)
'<html><body><h3/><p>Hallo</p></body></html>'

解析器可能做了这个 -turned h3进入空元素 - 因为它认为标题标签内的段落无效(而标题内的跨度有效):Is it valid to have paragraph elements inside of a heading tag in HTML5 (P inside H1)?

保持p里面的元素h3您可以尝试使用不同的解析器,即使用 BeautifulSoup's parser :

>>> from lxml.html import soupparser
>>> result = "<h3><p>Hallo</p></h3>"
>>> tree = soupparser.fromstring(result)
>>> etree.tostring(tree)
'<html><h3><p>Hallo</p></h3></html>'

关于python - xpath <p> 里面 <h3> 空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48235459/

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