【问题标题】:lxml and <noscript> in <head><head> 中的 lxml 和 <noscript>
【发布时间】:2015-12-02 22:45:11
【问题描述】:

我遇到了一个关于 lxml 的奇怪错误:

>>> s = '<html><head><noscript></noscript><script></script><meta></head></html>' 
>>> root = lxml.html.fromstring(s)
>>> root.xpath('/html/head/meta')
>>> root.xpath('/html/body/meta')
[<Element meta at 0x2a92788>]

meta 标签应该在 head 元素中,而不是 body。在这种情况下如何获得正确的元素?

【问题讨论】:

    标签: python lxml noscript lxml.html


    【解决方案1】:

    让我猜猜:您使用的是旧版本的 Ubuntu(如 12.04)吗? 实际上,这是 lxml 包使用的预装 libxml2 库的旧版本中的一个错误。在 2.8.0 版的 release notes 中,他们提到了 HTML parser error with &lt;noscript&gt; in the &lt;head&gt; 的修复 - 所以我猜 libxml2 >= 2.8.0 的版本应该可以工作。 Ubuntu 12.04 已安装 2.7.8 版本。

    >>> import lxml.etree
    >>> lxml.etree.LIBXML_COMPILED_VERSION
    (2, 7, 8)
    >>> lxml.etree.LIBXML_VERSION
    (2, 9, 1)
    

    我认为如果这些版本中的任何一个 >=2.8.0,&lt;noscript&gt; 问题应该消失了。

    【讨论】:

      【解决方案2】:

      这对我有用:

      import lxml.html
      
      s = '<html><head><noscript></noscript><script></script><meta></head></html>' 
      root = lxml.html.fromstring(s)
      print(root.xpath('/html/head/meta'))
      print(root.xpath('/html/body/meta'))
      

      输出:

      [<Element meta at 0x10a123b8>]
      []
      

      我正在使用 Python 2.7.9 和 lxml 版本 3.4.2。

      【讨论】:

      • 但是我收到了这个错误:AttributeError: 'module' object has no attribute 'html'
      • 通过from lxml import etreeetree.LXML_VERSION检查您使用的lxml版本。我正在努力复制您的问题
      • 我使用的是 Python 2.7.3 和 LXML 3.4.4
      • 我稍后会尝试升级Python并重新检查。谢谢!
      • @Kid,你的 AttributeError,尝试相对导入:from lxml import html 并将 lxml.html.fromstring 的用法更改为 html.fromstring
      猜你喜欢
      • 1970-01-01
      • 2011-09-22
      • 2020-12-07
      • 2011-10-26
      • 2013-04-12
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2016-03-11
      相关资源
      最近更新 更多