使用 ElementTree 解析包括标准实体的 XHTML

Parsing XHTML including standard entities using ElementTree

考虑以下片段:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head><title>&copy;</title></head>
  <body></body>
</html>

根据 W3C 的验证器 (https://validator.w3.org/),它被认为是有效的 XHTML 1.0 过渡版。然而,Python (3.7) 的 ElementTree 用

阻塞了它
$ python -c 'from xml.etree import ElementTree as ET; ET.parse("foo.html")'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python3.7/xml/etree/ElementTree.py", line 1197, in parse
    tree.parse(source, parser)
File "/usr/lib/python3.7/xml/etree/ElementTree.py", line 598, in parse
    self._root = parser._parse_whole(source)
xml.etree.ElementTree.ParseError: undefined entity &copy;: line 4, column 15

请注意 &copy; 确实是(最终)在 xhtml-lat1.ent 中定义的实体。

有没有办法使用 ElementTree 解析此类文档? 建议手动将适当的 XML 定义添加到 HTML 内容(例如 <!ENTITY nbsp ' '>),但这并不是真正的通用解决方案(除非有人在 header 之前添加任何文件的所有定义,但似乎应该有更简单的东西?)。

提前致谢。

考虑一下 lxml

from lxml import html


root = html.fromstring("""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head><title>&copy;</title></head>
  <body></body>
</html>
""".strip())
print(root.head.getchildren()[0].text)
# '©'

&copy; 在 xml 中无效。 xml 包真正解析 xml 但不是 html。其实内置的html解析器做可以解析这个内容:

from html.parser import HTMLParser


parser = HTMLParser()
parser.feed("""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head><title>&copy;</title></head>
  <body></body>
</html>
""".strip())
# no error

不过它的api真的很难用哈哈。 lxml 提供等效的 api.