python urlencode

来源:互联网 发布:js prompt怎么取消判断 编辑:程序博客网 时间:2024/06/16 19:52

url中的query带有特殊字符(不是url的保留字)时需要进行编码。

当url中带有汉字时,需要特殊的处理才能正确编码,以下都只针对这种情形,当然也适用于纯英文字符的url。

(1) url编码

import urlliburl = 'http://test.com/s?wd=哈哈'url = url.decode('gbk', 'replace')url = url.encode('utf-8', 'replace'print urllib.urlencode({"name":url })结果: 'name=http%3a%2f%2ftest.com%2fs%3fwd%3d%e5%93%88%e5%93%88'

(2) url解码:

import urllibencoded_url = 'http%3a%2f%2ftest.com%2fs%3fwd%3d%e5%93%88%e5%93%88'print urllib.unquote(encoded_url).decode('utf-8', 'replace').encode('gbk', 'replace')

函数调用的参数以及结果都是utf-8编码的,所以在对url编码时,需要将参数串的编码从原始编码转换成utf-8,

对url解码时,需要将解码结果从utf-8转换成原始编码格式。

s.decode(“utf-8”, “ignore”) 忽略其中有异常的编码,仅显示有效的编码
s.decode(“utf-8”, “replace”) 替换其中异常的编码,这个相对来可能一眼就知道那些字符编码出问题了。

0 0
原创粉丝点击