python - xpath <p> 里面 <h3> 空

标签 python python-3.x xpath lxml

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

相关文章:

python - Pygame鼠标点击检测

python-3.x - NameError:未定义全局名称 'long'

python - 使用lxml从span中提取文本?

php - 如何使用xPath php获取值(value)

python - 你如何在 python 2.7 中使用 "os.path.isfile ()"和一组 "path"但一个变量文件名?

python - 可以使用 Python 在 Windows 证书存储中安装 exe 文件 pfx 文件

python - Pygame 迷宫游戏无法正确创建关卡

python - 根据时间列计算日期列中的值

python - 如何从航类预订网站 https ://reservations. airarabia.com 获取价格信息

python redis 客户端无法使用.hgetall(key) 获取现有哈希值