一、urllib2发送请求
一般html表单,data须要编写成标准的形式,调用urllib.urlencode()进行urlencode编码,编写完然后用问号衔接 加到url后面
import urllib2 url = 'http://www.baidu.com' req = urllib2.Request(url) response = urllib2.urlopen(req) print response.read() print response.geturl() print response.info()
urllib2用一个Request对象,来映射HTTP请求。并将这个请求传入urlopen()中去,返回response对象
Request =>Response http就是基于这样的请求/应答机制
response对象,是一个文件对象,能够调用read(),info(),geturl()等方法
response.read() 读取返回的内容
response.info()获取返回header
response.geturl() 获取实际訪问的url
urllib2使用同样的接口处理全部的URL头,比方能够这样创建一个ftp请求
req = urllib2.Request('ftp://duote.com')
二、POST请求
import urllib2 url = "http://www.duote.com/index?php" data = {"softname":"quicktime.exe","size":"18763","md5":"HEN35FLK3WP"} req = urllib2.Request(url,data) response = urllib2.urlopen(req) print response.read()
Request(url,data=None,headers={},orgin_req_host=None。univerifiable=False)
urlopen(url, data=None, timeout=<object object>, cafile=None, capath=None, cadefault=False, context=None)
import urllib import urllib2 url = "http://www.2345.com" data = {'name':'Tom','age':'18','studynum':'002195'} urlvalue = urllib.urlencode(data) print urlvalue r_url = url +'?' +urlvalue data = urllib2.urlopen(r_url)
一般html表单,data须要编写成标准的形式,调用urllib.urlencode()进行urlencode编码,编写完然后用问号衔接 加到url后面