如何将 *所有* 字符转义为 Python 中相应的 html 实体名称和数字?

How can I escape *all* characters into their corresponding html entity names and numbers in Python?

我想将一个字符串编码为其对应的 html 实体,但不幸的是我做不到。正如我在问题标题中所说,我希望将字符串中的 all 个字符转换为相应的 html 实体(包括数字和名称)。所以根据documentation。我试过了:

In [31]: import html

In [32]: s = '<img src=x onerror="javascript:alert("XSS")">'

In [33]: html.escape(s)
Out[33]: '&lt;img src=x onerror=&quot;javascript:alert(&quot;XSS&quot;)&quot;&gt;'

但我希望转换所有字符,而不仅仅是“<”、“>”、“&”等。 而且 html.escape 只给出 html 实体 names 而不是数字,但我想要两者。

但令人惊讶的是 html.unescape 将所有实体转义为相应的字符。

In [34]: a = '<img src=x onerror="&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#000005
    ...: 8&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041">'

In [35]: html.unescape(a)
Out[35]: '<img src=x onerror="javascript:alert(\'XSS\')">' 

那么我可以对 html.escape 做同样的事情吗?

我真的很惊讶为什么 所有 互联网上用于编码和解码的资源 html 实体没有编码所有字符以及 php htmlspecialchars() 函数不要那样做。而且我不想一个字符一个字符地写出 here 中的所有 html 个实体编号。

对于您正在做的事情,您真的不需要特殊的功能,因为您想要的数字只是相关字符的 Unicode 代码点。

ord 几乎可以满足您的需求:

 def encode(s):
     return ''.join('&#{:07d};'.format(ord(c)) for c in s)

在美学上,我更喜欢十六进制编码:

 def encode(s):
     return ''.join('&#x{:06x};'.format(ord(c)) for c in s)

html.escape and html.unescape 的特别之处在于,除了数字实体之外,它们还支持命名实体。转义的目的通常是将您的字符串转换为不包含 HTML 解析器特殊字符的内容,因此 escape 仅替换少数字符。你正在做的是确保字符串中的所有字符除此之外都是 ASCII。

如果您想尽可能强制使用命名实体,您可以在将 ord 应用到字符后检查 html.entities.codepoint2name 映射:

def encode(s):
    return ''.join('&{};'.format(codepoint2name.get(i, '#{}'.format(i))) for i in map(ord, s))