Javascript unescape()与Python urllib.unquote()对比

6 投票
1 回答
7126 浏览
提问于 2025-04-18 03:18

从我阅读的各种帖子来看,JavaScript的unescape()函数和Python的urllib.unquote()函数是相似的。不过,当我测试这两个函数时,得到的结果却不一样:

在浏览器控制台中:

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

输出: <br>

在Python解释器中:

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

输出: %u003c%u0062%u0072%u003e

我本以为Python也会返回<br>。请问我这里有什么遗漏的吗?

谢谢!

1 个回答

11

%uxxxx是一种非标准的URL编码方式,在Python 3中不支持通过urllib.parse.unquote()来解码,而在Python 2中则不能通过urllib.unquote()来解码。

这种编码方式只在ECMAScript的第三版(ECMA-262 3rd edition)中出现过;但是这个格式被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%uxx这两种格式,这两种格式是ECMAScript第三版可以解码的。

示例:

>>> 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>'

不过,如果可以的话,最好还是避免使用这种编码方式。

撰写回答