urllib2是python自带的模块,有简单请求方法,也有复杂的http验证,http代理方法,今天就介绍几个基本的http请求方法
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://test.nginxs.net/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通过http请求发送数据给zabbix登录(非api的登录)
url = ‘http://192.168.198.116/index.php‘ data = {‘name‘ : ‘admin‘, ‘password‘ : ‘zabbix‘, ‘enter‘ : ‘Sign in‘ } data = urllib.urlencode(data) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() print the_page
urllib2验证nginx的用户进行登录
In [32]: auth_handler = urllib2.HTTPBasicAuthHandler() In [33]: top_level_url = ‘http://test.nginxs.net/limit/views.html‘ In [34]: username=‘admin‘ In [35]: password=‘nginxs.net‘ In [36]: auth_handler.add_password(realm=‘Nginxs.net login‘,uri=‘http://test.nginxs.net/limit/views.html‘,user=username,passwd=password) In [37]: opener = urllib2.build_opener(auth_handler) In [38]: urllib2.install_opener(opener) In [39]: urllib2.urlopen(top_level_url) Out[39]: <addinfourl at 61183328 whose fp = <socket._fileobject object at 0x3b29650>> In [40]: res=urllib2.urlopen(top_level_url) In [41]: print res.read() this is my web login success
时间: 2024-09-30 14:11:46