URL的编码、解码

 通常如果一样东西需要编码,说明这样东西并不适合传输。原因多种多样,如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

2

3

>>> import urllib

>>> urllib.quote("河源")

'%E6%B2%B3%E6%BA%90

python3:AttributeError: module 'urllib' has no attribute 'quote'原因

python2 与python3版本不兼容的问题真是让人诟病,现在又报错了,我的错误信息为:

 
  1. Traceback (most recent call last):

  2. File "/Users/eric/Documents/pythonFiles/aliyunxiaomi/chatwithxiaomi/chatwithali.py", line 22, in <module>

  3. canstring += '&' + percentEncode(k) + '=' + percentEncode(v)

  4. File "/Users/eric/Documents/pythonFiles/aliyunxiaomi/chatwithxiaomi/chatwithali.py", line 14, in percentEncode

  5. res = urllib.quote(str.decode(sys.stdin.encoding).encode('utf8'), '')

  6. AttributeError: module 'urllib' has no attribute 'quote'


然后,查阅相关资料,我的修改为:

 
  1. import urllib.parse

  2. def percentEncode(str):

  3. res = urllib.parse.quote(str, '')

  4. res = res.replace('+', '%20')

  5. res = res.replace('*', '%2A')

  6. res = res.replace('%7E', '~')

  7. return res


这样就不包错误了。

猜你喜欢

转载自blog.csdn.net/weixin_42670402/article/details/82939636
今日推荐