Python3网络爬虫——(4)urllib.error异常处理
生活随笔
收集整理的這篇文章主要介紹了
Python3网络爬虫——(4)urllib.error异常处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
異常處理 1、使用URLError進行異常處理 # -*- coding: UTF-8 -*-
from urllib import request
from urllib import error
if __name__ == "__main__":url = 'https://blog.csdn.net/asialee_bir' #錯誤鏈接try:response=request.urlopen(url)file=response.read().decode('utf-8')print(file)except error.URLError as e:print(e.code)print(e.reason)
2、使用HTTPError進行異常處理 # -*- coding: UTF-8 -*- from urllib import request from urllib import error if __name__ == "__main__":url = 'https://blog.csdn.net/asialee_bir' #錯誤鏈接try:response=request.urlopen(url)file=response.read().decode('utf-8')print(file)except error.HTTPError as e:print(e.code) #返回狀態碼print(e.reason) 異常結果:(403錯誤表示禁止訪問)
3、URLError和TTPError混合使用 # -*- coding: UTF-8 -*- from urllib import request from urllib import error if __name__ == "__main__":url = 'https://blog.baidusss.net' #不存在的鏈接try:response=request.urlopen(url)file=response.read().decode('utf-8')print(file)except error.URLError as e:if hasattr(e,'code'): #使用hasattr()判斷是否有這些屬性print('HTTPError')print(e.code)if hasattr(e,'reason'):print('URLError')print(e.reason)
異常結果:(403錯誤表示禁止訪問)
2、使用HTTPError進行異常處理 # -*- coding: UTF-8 -*- from urllib import request from urllib import error if __name__ == "__main__":url = 'https://blog.csdn.net/asialee_bir' #錯誤鏈接try:response=request.urlopen(url)file=response.read().decode('utf-8')print(file)except error.HTTPError as e:print(e.code) #返回狀態碼print(e.reason) 異常結果:(403錯誤表示禁止訪問)
注意:URLError是HTTPError的父類
3、URLError和TTPError混合使用 # -*- coding: UTF-8 -*- from urllib import request from urllib import error if __name__ == "__main__":url = 'https://blog.baidusss.net' #不存在的鏈接try:response=request.urlopen(url)file=response.read().decode('utf-8')print(file)except error.URLError as e:if hasattr(e,'code'): #使用hasattr()判斷是否有這些屬性print('HTTPError')print(e.code)if hasattr(e,'reason'):print('URLError')print(e.reason)
總結
以上是生活随笔為你收集整理的Python3网络爬虫——(4)urllib.error异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3.7 su命令 3.8 sudo命令
- 下一篇: Exception in thread