python urllib2 抓取网页 如何捕获各种异常呢

power0811 2010-01-06 05:16:04
我用python的 urllib2来抓取网页 怎么才能捕获各种返回的异常呢?
有如下代码:

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
是怎么回事 为什么说我未定义呢?
该怎么改才可以呢
还有 麻烦告知一下 网页各种返回错误怎么捕获呢
...全文
1164 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
notax 2010-01-07
  • 打赏
  • 举报
回复
[Quote=引用楼主 power0811 的回复:]
我用python的 urllib2来抓取网页 怎么才能捕获各种返回的异常呢?
有如下代码:
Python codeimport urllib2if__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
是怎么回事 为什么说我未定义呢?
该怎么改才可以呢
还有 麻烦告知一下 网页各种返回错误怎么捕获呢
[/Quote]

python 2.6

except urllib2.URLError, e:

or

except Exception, e: #捕获各种已定义返回错误

or

try
.....
except: #catch all exceptions
print sys.exc_info() #print all traceback exceptions, for debugging

damingg 2010-01-07
  • 打赏
  • 举报
回复
可能是没导入合适的库
不是有个更好的例子么
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

37,722

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧