我开始在 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/