【Python爬虫】异常处理

异常处理

方法一

# 异常处理
from urllib.request import Request,urlopen
from urllib.error import URLError,HTTPError
req = Request('https://www.baidu.com')
try:
    response = urlopen(req)
except HTTPError as e:
    print('出错')
    print('Error code:',e.code)
except URLError as e:
    print('Reason:',e.reason)
else:
    print('OK')

方法二

from urllib.request import Request,urlopen
from urllib.error import URLError
req = Request('https://www.baidu.com11')
try:
    response = urlopen(req)
except URLError as e:
    if hasattr(e,'reason'):
        print('Reason:',e.reason)
    elif hasattr(e,'code'):
        print('Error code:',e.code)
else:
    print('OK')

猜你喜欢

转载自blog.csdn.net/qq_36477513/article/details/114001993