我想将字符串编码为其相应的 html 实体,但不幸的是我无法做到。正如我在问题标题中所说,我想要all字符串中的字符将被转换为相应的 html 实体(数字和名称)。所以根据文档 https://docs.python.org/3/library/html.html。我试过:
In [31]: import html
In [32]: s = '<img src=x onerror="javascript:alert("XSS")">'
In [33]: html.escape(s)
Out[33]: '<img src=x onerror="javascript:alert("XSS")">'
但我希望所有字符都被转换,而不仅仅是 ''、 '&' 等。
并且html.escape
只给出html实体names不是数字,但我两者都想要。
但令人惊讶的是html.unescape https://docs.python.org/3/library/html.html#html.unescape将所有实体转义为其相应的字符。
In [34]: a = '<img src=x onerror="javascript
...: 8alert('XSS')">'
In [35]: html.unescape(a)
Out[35]: '<img src=x onerror="javascript:alert(\'XSS\')">'
那么我可以做同样的事情吗html.escape https://docs.python.org/3/library/html.html#html.escape?
我真的很惊讶为什么all互联网上用于编码和解码 html 实体的资源并未对所有字符以及 php 进行编码htmlspecialchars()
函数不这样做。我不想写出所有的 html 实体编号here https://www.freeformatter.com/html-entities.html逐个字符。
对于您正在做的事情,您实际上并不需要特殊的函数,因为您想要的数字只是相关字符的 Unicode 代码点。
ord https://docs.python.org/3/library/functions.html#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 https://docs.python.org/3/library/html.html#html.escape and html.unescape https://docs.python.org/3/library/html.html#html.unescape是它们除了数字实体之外还支持命名实体。转义的目标通常是将字符串转换为不包含 HTML 解析器特有字符的字符串,因此escape
仅替换少数字符。除此之外,您所做的还确保字符串中的所有字符都是 ASCII。
如果您想尽可能强制使用命名实体,您可以检查html.entities.codepoint2name https://docs.python.org/3/library/html.entities.html#html.entities.codepoint2name应用后映射ord
给角色:
def encode(s):
return ''.join('&{};'.format(codepoint2name.get(i, '#{}'.format(i))) for i in map(ord, s))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)