通常如果一样东西需要编码,说明这样东西并不适合传输。原因多种多样,如Size过大,包含隐私数据。对于Url来说,之所以要进行编码,是因为Url中有些字符会引起歧义。
例如,Url参数字符串中使用key=value键值对这样的形式来传参,键值对之间以&符号分隔,如/s?q=abc&ie=utf-8。如果你的value字符串中包含了=或者&,那么势必会造成接收Url的服务器解析错误,因此必须将引起歧义的&和=符号进行转义,也就是对其进行编码。
又如,Url的编码格式采用的是ASCII码,而不是Unicode,这也就是说你不能在Url中包含任何非ASCII字符,例如中文。否则如果客户端浏览器和服务端浏览器支持的字符集不同的情况下,中文可能会造成问题。
import urllib rawurl=xxx url=urllib.unquote(rawurl)
所用模块:urllib
所用函数:urllib.unquote()
案例
import urllib rawurl = "%E6%B2%B3%E6%BA%90" url = urllib.unquote(rawurl) print url
输出
河源
问题扩展
urllib.unquote()目的是对url编码进行解码,与该函数对应的是编码函数urllib.quote()
1
扫描二维码关注公众号,回复:
3485044 查看本文章
2 3 |
|
python3:AttributeError: module 'urllib' has no attribute 'quote'原因
python2 与python3版本不兼容的问题真是让人诟病,现在又报错了,我的错误信息为:
-
Traceback (most recent call last):
-
File "/Users/eric/Documents/pythonFiles/aliyunxiaomi/chatwithxiaomi/chatwithali.py", line 22, in <module>
-
canstring += '&' + percentEncode(k) + '=' + percentEncode(v)
-
File "/Users/eric/Documents/pythonFiles/aliyunxiaomi/chatwithxiaomi/chatwithali.py", line 14, in percentEncode
-
res = urllib.quote(str.decode(sys.stdin.encoding).encode('utf8'), '')
-
AttributeError: module 'urllib' has no attribute 'quote'
然后,查阅相关资料,我的修改为:
-
import urllib.parse
-
def percentEncode(str):
-
res = urllib.parse.quote(str, '')
-
res = res.replace('+', '%20')
-
res = res.replace('*', '%2A')
-
res = res.replace('%7E', '~')
-
return res
这样就不包错误了。