【问题标题】:Parsing XHTML using xml.etree.ElementTree使用 xml.etree.ElementTree 解析 XHTML
【发布时间】:2013-03-02 19:04:01
【问题描述】:

我想在 Python 3 中使用 xml.etree.ElementTree 解析 XHTML 文档。该文档包含   实体,因此我无法使用默认解析器设置。我想做类似的事情:

with urllib.request.urlopen(BASE_URL) as url:
        body = url.read()
        parser = ET.XMLParser()
        parser.parser.UseForeignDTD(True)
        parser.entity.update(entitydefs)
        etree = ET.ElementTree()
        root = etree.fromstring(body)

fromstringElementTree 中的免费功能。如何使用ElementTree 实例实现类似的功能?

【问题讨论】:

    标签: python xml-parsing elementtree


    【解决方案1】:

    好吧,我遇到了同样的问题。问题中的示例代码和选择的答案可能以前可以工作,但现在它不能在我的 Python 3.3 和 Python 3.4 环境中工作。

    我终于让它工作了。引用自Q&A

    this post 的启发,我们可以在传入的原始 HTML 内容之前添加一些 XML 定义,然后 ElementTree 就可以开箱即用了。

    这适用于 Python 2.6、2.7、3.3、3.4。

    import xml.etree.ElementTree as ET
    
    html = '''<html>
        <div>Some reasonably well-formed HTML content.</div>
        <form action="login">
        <input name="foo" value="bar"/>
        <input name="username"/><input name="password"/>
    
        <div>It is not unusual to see &nbsp; in an HTML page.</div>
    
        </form></html>'''
    
    magic = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [
                <!ENTITY nbsp ' '>
                ]>'''  # You can define more entities here, if needed
    
    et = ET.fromstring(magic + html)
    

    【讨论】:

      【解决方案2】:

      输入解析器:

      with urllib.request.urlopen(BASE_URL) as url:
          body = url.read()
          parser = ET.XMLParser()
          parser.parser.UseForeignDTD(True)
          parser.entity.update(entitydefs)
          parser.feed(body)
          root = parser.close()   # this returns you the tree
      

      【讨论】:

      • 原发帖者要求提供 Python 3 解决方案,但 parser.parser.UseForeignDTD(True) 在 Python 3 中不起作用。为什么选择此答案作为正确答案?
      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      相关资源
      最近更新 更多