参考官方文档:https://docs.python.org/2/howto/urllib2.html#urllib-howto
Quick reference to HTTP headers:http://jkorpela.fi/http.html
发送GET请求
>>> import urllib
>>> data = {}
>>> data['name'] = 'Somebody Here'
>>> data['location'] = 'Northampton'
>>> data['language'] = 'Python'
>>> url_values = urllib.urlencode(data)
>>> print url_values
name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values
>>> print full_url
http://www.example.com/example.cgi?name=Somebody+Here&language=Python&location=Northampton
发送POST请求
import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
发送POST请求(添加Headers)
import urllib
import urllib2
# 添加user_agent
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
# 添加user_agent
headers = {'User-Agent': user_agent}
data = urllib.urlencode(values)
# 添加user_agent
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
网友评论