【问题标题】:browser and HTMLPaser entities parsing difference浏览器和 HTMLPaser 实体解析的区别
【发布时间】:2017-08-31 21:09:35
【问题描述】:

我在网页的 HTML 中有以下字符 —。它在网页上呈现为“”(EM DASH)(如果需要,通过 Google Chrome 浏览器)。无论我如何使用文件编码(“utf-8”、“cp1251”、“cp866”),网页上始终是“—”。但是当我运行以下 python 代码时:

from HTMLParser import HTMLParser

h_parser = HTMLParser()
print h_parser.unescape('—')

它在unicode表中输出一些控制符号,即“保护区域结束”。

我应该使用什么 Python 代码从 — 字符串/unicode 字符串中获取“—”。我用python2.7

【问题讨论】:

    标签: python html python-2.7 html-entities


    【解决方案1】:

    字符引用中的数值(在您的情况下为 151)指的是 Unicode 代码点 151 (0x97),它在 Latin-1 Supplement 中表示控制字符。

    很可能正在使用无效值 151,因为它对应于 Windows 代码页 1252 中的短划线字符。浏览器将其呈现为短划线可能是为了处理这个常见错误。

    破折号的正确字符引用是&#8212

    >>> import unicodedata
    >>> unicodedata.name(unichr(151))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: no such name
    
    >>> unicodedata.lookup('em dash')
    u'\u2014'
    >>> unicodedata.lookup('em dash').encode('cp1252')
    '\x97'
    

    虽然 Python 2 遇到了这个问题,但在 Python 3 中,html.unescape() 函数显式处理 HTML 5 spec 中指定的无效字符引用。如果可能,您可以使用 Python 3 来解决您的问题:

    >>> from html import unescape
    >>> unescape('&#151;')
    '—'
    

    如果您不能使用 Python 3,您可以从 Python 3 html 模块复制代码(请参阅 __init__.py 文件)并在传递给 HTMLParser 之前通过它传递 HTML 代码。

    【讨论】:

      猜你喜欢
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多