Javascript unescape() 与 Python urllib.unquote()

2023-11-26

从阅读各种帖子来看,这似乎是 JavaScript 的unescape()相当于Pythonurllib.unquote(),但是当我测试两者时,我得到不同的结果:

在浏览器控制台中:

unescape('%u003c%u0062%u0072%u003e');

output: <br>

在Python解释器中:

import urllib
urllib.unquote('%u003c%u0062%u0072%u003e')

output: %u003c%u0062%u0072%u003e

我希望 Python 也能回归<br>。关于我在这里缺少什么有什么想法吗?

Thanks!


%uxxxx is a 非标准URL编码方案不支持urllib.parse.unquote()(Py 3)/urllib.unquote() (Py 2).

它只是 ECMAScript ECMA-262 第三版的一部分;该格式被 W3C 拒绝,并且从未成为 RFC 的一部分。

您可以使用正则表达式来转换此类代码点:

try:
    unichr  # only in Python 2
except NameError:
    unichr = chr  # Python 3

re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: unichr(int(m.group(1), 16)), quoted)

这解码了%uxxxx%uxxECMAScript 第三版可以解码。

Demo:

>>> import re
>>> quoted = '%u003c%u0062%u0072%u003e'
>>> re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: chr(int(m.group(1), 16)), quoted)
'<br>'
>>> altquoted = '%u3c%u0062%u0072%u3e'
>>> re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: chr(int(m.group(1), 16)), altquoted)
'<br>'

但如果可能的话,您应该避免完全使用编码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript unescape() 与 Python urllib.unquote() 的相关文章