Python实现unescape解码JS(escape,encodeURI等方法)url编码字符串

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

转载:

Python实现unescape解码JS(escape,encodeURI等方法)url编码字符串-CJavaPy

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 %%% 你好'

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值