32221sdad 发表于 2016-1-5 08:23:58

python urllib2使用小记

如何发送数据和加入多个header字段

1
2
3
4
5
6
7
8
request = urllib2.Request(url)
request.add_header("Content-Type", "application/json;charset=UTF-8")
request.add_header("User-Agent", "user_agent")

data = {'name': 'aaa', 'location': 'bbb'}
post_data = urllib.urlencode(data)

response = urllib2.urlopen(request, post_data)





关于发送数据的编码,urlencode(data)不是万能的,可以结合chrome的developer tools来查看发送过去的数据格式到底是怎样的。我就碰到过一次需要采用以下编码方式

1
str(data).replace("'",'"')




chrome developer tools如下图:



页: [1]
查看完整版本: python urllib2使用小记