網絡超時

  在訪問一個網頁時,若是該網頁長時間未響應,系統會判斷該網頁超時,因此沒法打開網頁。下面經過代碼來模擬一個網絡超時的現象,以下:網絡

import requests

for a in range(1,50):
    try:
        #
        response=requests.get('https://www.baidu.com/',timeout=0.05)
        print(response.status_code)
    except Exception as e:
        print('異常'+str(e))

 

提及網絡異常信息,requsets模塊提供了三種常見的網絡異常類,以下:spa

import requests

from requests.exceptions import ReadTimeout,HTTPError,RequestException

for a in range(1,50):
    try:
        response=requests.get('https://www.baidu.com/',timeout=0.05)
        print(response.status_code)
    except ReadTimeout:
        print('timeout')
    except HTTPError:
        print('httperror')
    except RequestException:
        print('reqerror')
相關文章
相關標籤/搜索