运维python拓展 urllib2使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了运维python拓展 urllib2使用相关的知识,希望对你有一定的参考价值。

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


本文出自 “nginxs小白” 博客,转载请与作者联系!

以上是关于运维python拓展 urllib2使用的主要内容,如果未能解决你的问题,请参考以下文章

Python2 urllib2用不了???求解。。。

每个 Python 开发者必备的5款 VScode 拓展工具包!

Python 2.7 urllib2 在使用 xml 内容点击重定向时引发 urllib2.HTTPError 301

在 python 中使用 urllib2 和 Tor 拒绝连接

代理背后的 Python 请求

Python URLLib / URLLib2 POST