urllib2模块之异常处理

简介:

一、urllib2模块回顾

        urllib2模块中最重要的函数是urlopen()函数,用于获取URLs资源(Uniform Resorce Locators)。urlopen函数不仅可以用于简单的情况,还可以进行复杂情况下的资源获取如认证(authentication)、cookies、代理等。urlopen支持多种协议,如http、ftp、file等。

        HTTP是基于请求、响应的协议,客户端发出请求、服务器端作出响应。urllib2通过Request对象反映发出的HTTP请求,调用urlopen()时就会发出请求,函数返回值就是相应的响应对象。

1、POST数据

我们下面做个最简单的post数据提交的测试,当然很多情况下这种简单的测试是提交不成功的,但是我们可以从中学习的post数据的用法

[python] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #!/usr/bin/python  
  2. #coding=utf-8  
  3.   
  4. import urllib  
  5. import urllib2  
  6.   
  7.   
  8. user        =   "yourname"  
  9. password    =   "password"   
  10. postUrl     =  "http://www.xiami.com/member/login"  
  11. postData    =   {   'email'     :   user,   
  12.                     'password'  :   password,   
  13.                     'autologin' :   '1',   
  14.                     'submit'    :   '登 录',   
  15.                     'type'      :   ''  
  16. }  
  17.   
  18.   
  19. req         =   urllib2.Request(postUrl)  
  20. postData    =   urllib.urlencode(postData)  
  21. #enable cookie  
  22. opener      =   urllib2.build_opener(urllib2.HTTPCookieProcessor())  
  23. response    =   opener.open(req, postData)   
  24.   
  25. print response.read( )  
#!/usr/bin/python
#coding=utf-8

import urllib
import urllib2


user        =   "yourname"
password    =   "password" 
postUrl     =  "http://www.xiami.com/member/login"
postData    =   {   'email'     :   user, 
                    'password'  :   password, 
                    'autologin' :   '1', 
                    'submit'    :   '登 录', 
                    'type'      :   ''
}


req         =   urllib2.Request(postUrl)
postData    =   urllib.urlencode(postData)
#enable cookie
opener      =   urllib2.build_opener(urllib2.HTTPCookieProcessor())
response    =   opener.open(req, postData) 

print response.read( )


或者直接使用简化的写法
 

[python] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import urllib  
  2. import urllib2  
  3.    
  4. url     =   "http://www.example.com/"  
  5. datas   =   {   "email" : user,  
  6.                 "password" : password  
  7. }  
  8.   
  9. req     =   urllib2.Request(url,urllib.encode(datas))  
  10. response=   urllib2.urlopen(req)  
import urllib
import urllib2
 
url     =   "http://www.example.com/"
datas   =   {   "email" : user,
                "password" : password
}

req     =   urllib2.Request(url,urllib.encode(datas))
response=   urllib2.urlopen(req)

 

2、增加Header头部

          由于一些网站不希望被程序访问,或网站会发送不同的内容给不同的浏览器类型,因此需要修改HTTP头部来将程序伪造成相应的浏览器,而浏览器通常通过头部的User-Agent来识别,因此通常只改User-Agent即可。方法是传递一个headers头部字典给Request对象。

[python] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import urllib2  
  2.    
  3. url     =   "http://www.example.com/"  
  4. headers =   {"User-Agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}  
  5. request =   urllib2.Request(url, headers=headers)  
  6. response=   urllib2.urlopen(request)  
  7. print response.read( )  
import urllib2
 
url     =   "http://www.example.com/"
headers =   {"User-Agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}
request =   urllib2.Request(url, headers=headers)
response=   urllib2.urlopen(request)
print response.read( )

也可使用如下代码

[python] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import urllib2  
  2.    
  3. url      =   "http://www.example.com/"  
  4. request  = urllib2.Request(url)  
  5. request.add_header("User-Agent""Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")  
  6. response = urllib2.urlopen(request)  
  7. print response.read( )  
  8. response.close( )  
import urllib2
 
url      =   "http://www.example.com/"
request  = urllib2.Request(url)
request.add_header("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")
response = urllib2.urlopen(request)
print response.read( )
response.close( )


 二、异常处理

  当urlopen()不能处理响应时会引起URLError异常。HTTPError异常是URLError的一个子类,只有在访问HTTP类型的URL时才会引起。

1、URLError异常

    通常引起URLError的原因是:无网络连接(没有到目标服务器的路由)、访问的目标服务器不存在。在这种情况下,异常对象会有reason属性(是一个(错误码、错误原因)的元组)

[python] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #!coding:utf-8  
  2.   
  3. import urllib2  
  4.    
  5. url="http://www.baidu.com/"  
  6. try:  
  7.     response = urllib2.urlopen(url)  
  8.     print response.read( )  
  9. except urllib2.URLError, e:  
  10.     print e.reason  
#!coding:utf-8

import urllib2
 
url="http://www.baidu.com/"
try:
    response = urllib2.urlopen(url)
    print response.read( )
except urllib2.URLError, e:
    print e.reason

 

2、HTTPError

        每一个从服务器返回的HTTP响应都有一个状态码。其中,有的状态码表示服务器不能完成相应的请求,默认的处理程序可以为我们处理一些这样的状态码(如返回的响应是重定向,urllib2会自动为我们从重定向后的页面中获取信息)。有些状态码,urllib2模块不能帮我们处理,那么urlopen函数就会引起HTTPError异常,其中典型的有404/401。

        HTTPError异常的实例有整数类型的code属性,表示服务器返回的错误状态码。

        urllib2模块默认的处理程序可以处理重定向(状态码是300范围),而且状态码在100-299范围内表示成功。因此,能够引起HTTPError异常的状态码范围是:400-599.  

        当引起错误时,服务器会返回HTTP错误码和错误页面。你可以将HTPError实例作为返回页面,这意味着,HTTPError实例不仅有code属性,还有read、geturl、info等方法。

[python] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #!coding=utf-8  
  2.   
  3. import urllib2  
  4.    
  5. url="http://www.csdn.net/aderstep"  
  6. try:  
  7.     response=urllib2.urlopen(url)  
  8. except urllib2.HTTPError, e:  
  9.     print e.code  
  10.     print e.read()  
#!coding=utf-8

import urllib2
 
url="http://www.csdn.net/aderstep"
try:
    response=urllib2.urlopen(url)
except urllib2.HTTPError, e:
    print e.code
    print e.read()

 

三、总结

    如果想在代码中处理URLError和HTTPError有两种方法,代码如下:

[python] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #!coding:utf-8  
  2. import urllib2  
  3.   
  4. url     = "http://www.csdn.com/aderstep"  
  5. request = urllib2.Request(url)  
  6. request.add_header("User-Agent""Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")  
  7. try:  
  8.     response = urllib2.urlopen(request)  
  9.     print response.read( )  
  10.     response.close( )  
  11.     # HTTPError必须排在URLError的前面  
  12.     # 因为HTTPError是URLError的子类对象  
  13.     # 在网访问中引发的所有异常要么是URLError类要么是其子类  
  14.     # 如果我们将URLError排在HTTPError的前面,那么将导致HTTPError异常将永远不会被触发  
  15.     # 因为Python在捕获异常时是按照从前往后的顺序挨个匹配的  
  16. except urllib2.HTTPError, e:  
  17.     print "The server couldn't fulfill the request"  
  18.     print "Error code:", e.code  
  19.     if e.code == 404:  
  20.         print "Page not found!"  
  21.         #do someting  
  22.     elif e.code == 403:  
  23.         print "Access denied!"  
  24.         #do someting  
  25.     else:  
  26.         print "Something happened! Error code", e.code  
  27.     print "Return content:", e.read()  
  28. except urllib2.URLError, err1:  
  29.     print "Failed to reach the server"  
  30.     print "The reason:", e.reason  
#!coding:utf-8
import urllib2

url     = "http://www.csdn.com/aderstep"
request = urllib2.Request(url)
request.add_header("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")
try:
    response = urllib2.urlopen(request)
    print response.read( )
    response.close( )
    # HTTPError必须排在URLError的前面
    # 因为HTTPError是URLError的子类对象
    # 在网访问中引发的所有异常要么是URLError类要么是其子类
    # 如果我们将URLError排在HTTPError的前面,那么将导致HTTPError异常将永远不会被触发
    # 因为Python在捕获异常时是按照从前往后的顺序挨个匹配的
except urllib2.HTTPError, e:
    print "The server couldn't fulfill the request"
    print "Error code:", e.code
    if e.code == 404:
        print "Page not found!"
        #do someting
    elif e.code == 403:
        print "Access denied!"
        #do someting
    else:
        print "Something happened! Error code", e.code
    print "Return content:", e.read()
except urllib2.URLError, err1:
    print "Failed to reach the server"
    print "The reason:", e.reason



 

或者使用如下的代码模版,也是用的最多的模版

[python] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #coding=utf-8  
  2. import urllib2  
  3.   
  4.   
  5. url     = "http://www.csdn.com/aderstep"  
  6. request = urllib2.Request(url)  
  7. request.add_header("User-Agent""Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")  
  8. try:  
  9.     response = urllib2.urlopen(request)  
  10.     print response.read( )  
  11.     response.close( )  
  12.   
  13. except urllib2.URLError, e:  
  14.     if hasattr(e, "reason"):  
  15.         print "Failed to reach the server"  
  16.         print "The reason:", e.reason  
  17.     elif hasattr(e, "code"):  
  18.         print "The server couldn't fulfill the request"  
  19.         print "Error code:", e.code  
  20.         print "Return content:", e.read()  


转载:http://blog.csdn.net/gatieme/article/details/43371901

目录
相关文章
|
6天前
|
Python
Python中使用`requests`库进行异常处理与调试
【4月更文挑战第12天】在Python的网络编程中,使用`requests`库发送HTTP请求时,经常会遇到各种异常情况,如网络连接错误、请求超时、服务器错误等。为了确保程序的健壮性和稳定性,我们需要对这些异常进行妥善处理,并进行必要的调试。本文将详细介绍如何在Python中使用`requests`库进行异常处理与调试。
|
6天前
|
UED 开发者 Python
Python中使用`requests`库进行重定向与超时控制的技术详解
【4月更文挑战第12天】在Web开发中,处理HTTP重定向和请求超时是常见的需求。`requests`库作为Python中处理HTTP请求的利器,提供了丰富的功能来满足这些需求。本文将详细探讨如何在Python中使用`requests`库进行重定向处理和超时控制。
|
8月前
|
搜索推荐 Python
Python 基于 urllib 使用 Handler 处理器(代理)
Python 基于 urllib 使用 Handler 处理器(代理)
52 0
|
4月前
|
数据采集 Python
urllib 库编写爬虫
urllib 库编写爬虫
114 5
|
11月前
|
数据采集 XML 存储
urllib模块的使用
urllib模块的使用
38 0
|
数据采集 编解码 Python
urllib的基础使用方法
urllib的基础使用方法
111 0
|
数据采集 Python
爬虫第一次笔记 urllib的基本使用 urllib一个类型,六个方法 urllib下载 urllib请求对象的定制
爬虫第一次笔记 urllib的基本使用 urllib一个类型,六个方法 urllib下载 urllib请求对象的定制
86 0
爬虫第一次笔记 urllib的基本使用 urllib一个类型,六个方法 urllib下载 urllib请求对象的定制
|
存储 数据采集 JavaScript
Python:urllib2模块Handler处理器 和 自定义Opener(二)
Python:urllib2模块Handler处理器 和 自定义Opener(二)
204 0
Python:urllib2模块Handler处理器 和 自定义Opener(二)
|
数据采集 数据安全/隐私保护 Python
Python:urllib2模块Handler处理器 和 自定义Opener(一)
Python:urllib2模块Handler处理器 和 自定义Opener(一)
158 0
Python:urllib2模块Handler处理器 和 自定义Opener(一)
|
数据采集 网络安全 Python
python爬虫——request模块讲解
python爬虫——request模块讲解
319 0
python爬虫——request模块讲解