python urllib2 抓取网页 如何捕获各种异常呢
我用python的 urllib2来抓取网页 怎么才能捕获各种返回的异常呢?
有如下代码:
Python code:
import urllib2
if __name__ == '__main__':
url = 'http://hh'
try:
urllib2.urlopen(url, timeout=5)
except URLError, e:
print e.reason
我捕获异常 却提示这种错误:
except URLError, e:
NameError: name 'URLError' is not defined
是怎么回事 为什么说我未定义呢?
该怎么改才可以呢
还有 麻烦告知一下 网页各种返回错误怎么捕获呢
可能是没导入合适的库
不是有个更好的例子么
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(someurl)
try:
response = urlopen(req)
except HTTPError, e:
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
except URLError, e:
print 'We failed to reach a server.'
print 'Reason: ', e.reason
else:
# everything is fine
相关问答:
请问下,我的是python2.5安装了PIL模块,然后编写程序打开本机上的一个图片时,为什么老出现错误呢,老是找不到图片,错误提示如下:File "C:\Python25\Lib\site-packages\PIL\Image.py", line 1888, in o ......
大家好,我是一个新手,刚开始学python,但是刚开始的helloworld都没法打印,让我很无奈。
我的python安装路径为f:\python31。在path中也设置对了,在windows下运行是这样显示的,希望各位前辈指点一下。谢谢
Pyth ......
在list中添加一个类的局部变量 这样做是否合法 请看下面例子:
Python code:
class A():
def __init__( self ):
self.__a = 0
self.__b = 'hello'
def get_a( self ):
ret ......