美文网首页
urllib2发送GET请求与POST请求

urllib2发送GET请求与POST请求

作者: tonyemail_st | 来源:发表于2017-11-05 10:26 被阅读0次

参考官方文档: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()

相关文章

网友评论

      本文标题:urllib2发送GET请求与POST请求

      本文链接:https://www.haomeiwen.com/subject/ppscmxtx.html