urllib2自定义opener详解
Jun 16, 2016 am 08:45 AMurllib2.urlopen()函数不支持验证、cookie或者其它HTTP高级功能。要支持这些功能,必须使用build_opener()函数创建自定义Opener对象。
build_opener([handler1 [ handler2, ... ]])
参数handler是Handler实例,常用的有HTTPBasicAuthHandler、HTTPCookieProcessor、ProxyHandler等。
build_opener ()返回的对象具有open()方法,与urlopen()函数的功能相同。
如果要修改http报头,可以用:
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')
2. install_opener(opener)
安装不同的opener对象作为urlopen()使用的全局opener。
3. 密码验证(HTTPBasicAuthHandler)
HTTPBasicAuthHandler()处理程序可用add_password()来设置密码。
h.add_password(realm,uri,user,passwd)
realm是与验证相关联的名称或描述信息,取决于远程服务器。uri是基URL。user和passwd分别指定用户名和密码。
import urllib2
auth=urllib2.HTTPBasicAuthHandler()
auth.add_password('Administrator','http://www.example.com','Dave','123456')
opener=urllib2.build_opener(auth)
u=opener.open('http://www.example.com/evilplan.html')
4. Cookie处理(HTTPCookieProcessor)
import urllib2,cookielib
cookie=cookielib.CookieJar()
cookiehand=urllib2.HTTPCookieProcessor(cookie)
opener=urllib2.build_opener(cookiehand)
5.代理(ProxyHandler)
ProxyHandler(proxies)参数proxies是一个字典,将协议名称(http,ftp)等映射到相应代理服务器的URL。
proxy=ProxyHandler({'http':'http://someproxy.com:8080'})
auth=HTTPBasicAuthHandler()
auth.add_password()
opener=build_opener(auth,proxy)
也可以在urlopen中使用代理
import urllib2
proxy = 'http://%s:%s@%s' % ('userName', 'password', 'proxy')
inforMation = urllib2.urlopen("http://www.example.com", proxies={'http':proxy})

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to quickly set up a custom avatar in Netflix

How to customize background image in Win11

How to create and customize Venn diagrams in Python?

How to create custom pagination in CakePHP?

render function in Vue3: custom rendering function

How to enable and customize crossfades in Apple Music on iPhone with iOS 17

How to implement custom middleware in CodeIgniter

How to customize shortcut key settings in Eclipse
