1

用例:

使用 lxml解析https://www.banca-romaneasca.ro/en/tools-and-resources/失败。

...
/opt/python-env/ciur/local/lib/python2.7/site-packages/html5lib/html5parser.py:468: in processComment
    self.tree.insertComment(token, self.tree.openElements[-1])
/opt/python-env/ciur/local/lib/python2.7/site-packages/html5lib/treebuilders/etree_lxml.py:312: in insertCommentMain
    super(TreeBuilder, self).insertComment(data, parent)
/opt/python-env/ciur/local/lib/python2.7/site-packages/html5lib/treebuilders/_base.py:262: in insertComment
    parent.appendChild(self.commentClass(token["data"]))
/opt/python-env/ciur/local/lib/python2.7/site-packages/html5lib/treebuilders/etree.py:148: in __init__
    self._element = ElementTree.Comment(data)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

- src/lxml/lxml.etree.pyx:3017: ValueError: Comment may not contain '--' or end with '-'

它来自 lxml > https://github.com/lxml/lxml/blob/master/src/lxml/lxml.etree.pyx#L3017

它在https://www.banca-romaneasca.ro/en/tools-and-resources/中发现了不好的评论

...
<script type="text/javascript" src="/_res/js/forms.js"></script>

<!-- Google Code for Remarketing Tag -->
<!--------------------------------------------------
Remarketing tags may not be associated with personally identifiable information or placed on pages related to sensitive categories. See more information and instructions on how to setup the tag on: http://google.com/ads/remarketingsetup
--------------------------------------------------->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 958631629;
var google_custom_params = window.google_tag_params;
... 

寻求解决方案,例如:

  • 禁用检查(一些魔法,标志,在 xml 上)

    if b'--' in text or text.endswith(b'-'):
        raise ValueError("Comment may not contain '--' or end with '-'")
    
  • 猴子补丁(更改代码,注入......)

更新1:

我使用 html5lib 并希望在 html5 中获得声音、部分、视频等标签。

from lxml.html import html5parser, fromstring

context = fromstring(document.content) # work    
context = html5parser.fromstring(document.content) # do not work

context = html5lib.parse(  # do not work
    document.content,
    treebuilder="lxml",
    namespaceHTMLElements=document.namespace,
    encoding=document.encoding
)

版本:

  • html5lib==0.9999999
  • lxml==3.5.0(降级 lxml 也不是解决方案)

更新 2::

这似乎是 lxml https://github.com/lxml/lxml/pull/172#issuecomment-169084439中的改进/问题。

等待 lxml 开发者反馈。

更新 3::

收到反馈,似乎是 html5lib 错误,来自 github 的最后一个开发版本已经修复。

4

2 回答 2

2

已找到解决方案,基于来自 github 的@opottone:

我尝试html5parsergithub安装最新版本。现在我只收到警告,而不是错误。

于 2016-01-06T11:36:10.257 回答
1

由于这是您尝试解析、使用lxml.html而不是lxml.etree.

为我工作:

>>> import requests
>>> import lxml.html
>>> 
>>> data = requests.get("https://www.banca-romaneasca.ro/en/tools-and-resources/").content
>>> tree = lxml.html.fromstring(data)
>>> tree.xpath("//title/text()")
['Tools and resources - Banca Romaneasca']
于 2016-01-04T16:16:11.887 回答