python爬虫--urllib2和requests

本文通过两个实例比较了urllib2和requests库在处理HTTP请求时的不同实现方式,并展示了它们在属性访问、认证处理及错误反馈方面的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • -

1、实例1

使用get方法从http://example.test/获取资源并且查看返回代码,content-type头信息,还有response的主体内容。

1.1 使用urllib2实现

import urllib2  

url = 'http://example.test/' 
response = urllib2.urlopen(url)  

response.getcode()  //200
response.headers.getheader('content-type')// 'text/html; charset=utf-8' 
response.read()   //'Hello, world!' 

2.1 使用requests实现

import requests  

 url = 'http://example.test/' 
response = requests.get(url)  

response.status_code  // 200 
response.headers['content-type'] //'text/html; charset=utf-8' 
response.content  //u'Hello, world!' 

3、区别

urllib2调用方法读取response中的属性信息;

Requests则是使用属性名来获取对应的属性值;
Requests 自动的把返回信息有Unicode解码;
Requests 自动保存了返回内容,所以你可以读取多次,而不像urllib2.urlopen()那样返回的只是一个类似文件类型只能读取一次的对象;

2、实例2

使用GET方法获取http://foo.test/secret的资源,这次需要基本的http验证;

2.1 urllib2实现

import urllib2  
url = 'http://example.test/secret' 

password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()   
password_manager.add_password(None, url, 'dan', 'h0tdish')  
auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)  
opener = urllib2.build_opener(auth_handler)  
urllib2.install_opener(opener)  

response = urllib2.urlopen(url)  
response.getcode()  //200 
response.read() //    'Welcome to the secret page!'

实例化了2个类,然后组建了第三个类,最后还要装载到全局的urllib2模块中;

HTTPPasswordMgr.add_password(realm, uri, user, passwd)

2.2 requests实现

import requests  
url = 'http://example.test/secret'
response = requests.get(url, auth=('dan', 'h0tdish'))  
response.status_code  //200
response.content  // u'Welcome to the secret page!'

requests实现简单:只是在调用方法的时候增加了一个auth关键字函数;

3、错误处理

对于认证,使用了不正确的用户名和密码,urllib2会引发一个urllib2.URLError错误;
而Requests 会返回一个正常的response对象,只需查看response.ok的布尔值便可以知道是否登陆成功:

response = requests.get(url, auth=('dan', 'wrongPass'))  
response.ok
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值