我用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