【问题标题】:xpath <p> inside <h3> emptyxpath <p> 内 <h3> 为空
【发布时间】:2018-06-22 11:00:49
【问题描述】:

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

非常感谢!

【问题讨论】:

    标签: python python-3.x xpath lxml


    【解决方案1】:

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

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

    解析器可能这样做了 - 将 h3 变成了空元素 - 因为它认为标题标签内的段落无效(而标题内的 span 有效):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>'
    

    【讨论】:

    • 有没有办法解决这个问题?我正在抓取网站,许多网站都使用这种语法。我可以以某种方式改变它读取 html 的方式吗?另外:我可以将 div-Elements 放在 h3 中,尽管 div 也不是“短语内容”-Element。
    • 谢谢!这有帮助!
    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 2018-12-11
    相关资源
    最近更新 更多