本文主要介绍Python(Python2和Python3)中,解析处理js(JavaScript)中通过escape(),encodeURI(),encodeURIComponent()对url字符串编码(encode),实现unescape对编码之后的字符串进行解码(decode)的方法代码。并且支持中文和换行(\r\n)等特殊字符。

1、Python2中unescape解码方法

通过pip安装urllib2、HTMLParser、re

import urllib2
import sys
import HTMLParser
import re
def unescape(string):
    string = urllib2.unquote(string).decode('utf8')
    quoted = HTMLParser.HTMLParser().unescape(string).encode(sys.getfilesystemencoding())
    #转成中文
    return re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: unichr(int(m.group(1), 16)), quoted)

调用:

>>> unescape("hello%20%25%25%25%20%u4F60%u597D")
u'hello %%% \u4f60\u597d'

2、Python3中unescape解码方法

import urllib.parse
import sys
import html
import re
def unescape(string):
    string = urllib.parse.unquote(string)
    quoted = html.unescape(string).encode(sys.getfilesystemencoding()).decode('utf-8')
    #转成中文
    return re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: chr(int(m.group(1), 16)), quoted)

调用:

>>> unescape('hello %%% %u4F60%u597D')
'hello %%% 你好'

注意:不要使用接替换%方式转换成中文,有可能有些情况是有问题的,比如字符串中原本就有%的情况。





推荐文档