![](/img/trans.png)
[英]How can I print entity numbers in my xml document instead of entity names using python's lxml?
[英]How can I escape *all* characters into their corresponding html entity names and numbers in Python?
我想将一个字符串编码为其相应的 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 实体名称而不是数字,但我想要两者。
但令人惊讶的是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
做同样的html.escape
吗?
我真的很惊讶为什么互联网上用于编码和解码 html 实体的所有资源都没有编码所有字符,而且 php htmlspecialchars()
函数也没有这样做。 而且我不想从这里一个字符一个字符地写出所有的 html 实体编号。
对于正在执行的操作,您实际上并不需要特殊函数,因为您想要的数字只是相关字符的 Unicode 代码点。
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
和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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.