您好,欢迎访问一九零五行业门户网

详解Python urlencode编码和url拼接方法

urlencode 调用方法urlencode的参数必须是dictionary
import urllib d = {'name1':'www.pythontab.com','name2':'bbs.pythontab.com'}print urllib.urlencode(d)
输出:
name2=bbs.pythontab.com&name1=www.pythontab.com
相当于拼接两个url参数,这个用法类似于php中的http_build_query(),这里就不多数php中怎么用了,有兴趣的自己去查一下。
urlencode 编码函数urlencode不会改变传入参数的原始编码,也就是说需要在调用之前将post或get参数的编码调整好。
问题:现在模拟请求google和baidu,由于baidu使用的是gb2312编码,google使用的是utf8编码,两个站点提交到url中的中文参数的urlencode值是不一样,下面以”pythontab中文网”为例:
# coding: utf-8 str = u'pythontab中文网' str = str.encode('gb2312') d = {'name':str} q = urllib.urlencode(d) print q
结果:
name=pythontab%d6%d0%ce%c4%cd%f8
注意:urlencode的参数必须是dictionary
其他用法django中urlencode类似,方法如下:
from django.utils.http import urlquote a = urlquote('pythontab中文网') print a
得到汉字的gbk编码
urllib 转换字符串其实可以用urllib的quote函数对url中的中文进行转换,将中文转换成gbk的编码,得到的编码是符合uri标准的url。
>>> import urllib >>> a = "pythontab中文网" >>> a 'pythontab\xe4\xb8\xad\xe6\x96\x87\xe7\xbd\x91' >>> urllib.quote(a) 'pythontab%e4%b8%ad%e6%96%87%e7%bd%91' >>>
以上就是详解python urlencode编码和url拼接方法的详细内容。
其它类似信息

推荐信息