urllib2是python自带的模块,有简单请求方法,也有复杂的http验证,http代理方法,今天就介绍几个基本的http请求方法。
urllib2的urlopen方法可以直接添加url即可访问,但是此方法不支持验证和代理的方法,所以后边会介绍urllib2的Request类和opener
urllib2.urlopen
urllib2.urlopen(url,data=None,timeout=1,cafile=None,capath=None,cadefault=False,context=None) 下面是urllib2发起http请求,获取httpcode
In [1]: import urllib2 In [2]: url = 'http:///index.html' In [3]: res = urllib2.urlopen(url) #读取请求结果 In [5]: print res.read() this is index.html #获取httpcode In [6]: print res.code 200 #获取http请求头 In [7]: print res.headers Server: nginxsweb Date: Sat, 07 Jan 2017 02:42:10 GMT Content-Type: text/html Content-Length: 19 Last-Modified: Sat, 07 Jan 2017 01:04:12 GMT Connection: close ETag: "58703e8c-13" Accept-Ranges: bytes
urllib2的Request
(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False)
通过http请求发送数据给zabbix登录(非api的登录)
import urllib
import urllib2
url = 'http://192.168.198.116/index.php'
#这里是zabbix的账户,密码,和点击的操作
data = {'name' : 'admin',
'password' : 'zabbix',
'enter' : 'Sign in' }
#编码上面的数据
data = urllib.urlencode(data)
#实例化Request类
req = urllib2.Request(url, data)
#发送请求
response = urllib2.urlopen(req)
the_page = response.read()
print the_pageurllib2.HTTPBasicAuthHandler
验证nginx的用户进行登录
#初始化一个auth_handler实例它的功能是http验证的类 auth_handler = urllib2.HTTPBasicAuthHandler() top_level_url = 'http:///limit/views.html' username='admin' password='nginxs.net' #调用auth_handler实例里面的密码方法 auth_handler.add_password(realm='Nginxs.net login',uri=' #构建一个opener 对象,它将使用http,https,ftp这三个默认的handlers opener = urllib2.build_opener(auth_handler) #安装一个opener作为全局urlopen()使用的对象 urllib2.install_opener(opener) res=urllib2.urlopen(top_level_url) print res.read()
urllib2.ProxyHandler
使用代理访问一个网站
url='http://new.nginxs.net/ip.php'
#初始化一个名为proxy代理实例
proxy = urllib2.ProxyHandler({'http':'127.0.0.1:1080'})
#这里创建一个opener对象,这个对象可以处理http,https,ftp等协议,如果你指定了子类参数这个默认的handler将不被使用
opener = urllib2.build_opener(proxy)
#使用open方法打开url
res = opener.open(url)
#查看返回结果
print res.read()先写这些,以后有时间再补充
















