【问题标题】:Differences with element tree and xpath元素树和 xpath 的区别
【发布时间】:2012-02-29 01:57:51
【问题描述】:

我正在尝试在元素树中查找一些节点,但这似乎会根据我用于解析的实现而有所不同。这似乎与文档不一致。我错过了什么吗?

In [52]: ElementTree.fromstring('<html><x /></html>').find('.//x')
Out[52]: <Element 'x' at 0x3008c10>

但是:

In [59]: type(html5lib.parse('<html><x /></html>', treebuilder='lxml').find('.//x'))
Out[59]: <type 'NoneType'>

我也尝试过使用 ElementTree 的 html5lib,但这似乎并没有运行符合文档的解析:

In [72]: parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder('etree', cElementTree))

In [73]: type(parser.parse('<html><x /></html>'))
Out[73]: <type 'NoneType'>

那么我该如何解决呢?我无法继续直接使用 ElementTree,因为它不会解析一些损坏的 html。

【问题讨论】:

    标签: python html parsing elementtree


    【解决方案1】:

    xpath() 似乎有效:

    >>> doc = html5lib.parse('<!doctype html><html><x /></html>', treebuilder='lxml')
    
    >>> doc.xpath('.//*')
        [<Element {http://www.w3.org/1999/xhtml}head at 0x102c04a50>,
     <Element {http://www.w3.org/1999/xhtml}body at 0x102c04aa0>,
     <Element {http://www.w3.org/1999/xhtml}x at 0x102c04af0>]
    
    >>> doc.xpath('.//html:x', namespaces={'html':'http://www.w3.org/1999/xhtml'})
        [<Element {http://www.w3.org/1999/xhtml}x at 0x102c04af0>]
    

    然而,html5lib 将 XHTML 命名空间分配给纯 HTML 是相当奇怪的。

    【讨论】:

    • 你的评论让我找到了解决方案:html5lib.parse(..., namespaceHTMLElements=False).xpath('.//x') 工作得很好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2021-04-26
    • 2011-11-19
    • 1970-01-01
    相关资源
    最近更新 更多