request類的各種ERROR

URLerror

URLError類繼承自OSError類,是urllib庫的error模塊的基類,由request操作產生的異常都可以通過捕獲該類來處理。它具有一個屬性reason,即返回錯誤的原因。

打開一個不存在的頁面

from urllib.request import *
from urllib.error import *
try:
    response = urlopen('https://www.zhihu.com/people/happy233333')
except URLError as e:
    print(e.reason)
Not Found
from urllib.request import *
from urllib.error import *
try:
     response = urlopen("https://qq.123.com")
except URLError as e:
    print(e.reason)
[Errno 11001] getaddrinfo failed
from urllib.request import *
from urllib.error import *
try:
     response = urlopen("https://www.google.com")
except URLError as e:
    print(e.reason)
[Errno 11003] getaddrinfo failed

上面的三個測試,第一個是訪問存在的知乎網站+不存在的博客名,第二個是訪問不存在的網站。第三個是訪問長城之外的網站。

URLError有時候也會是對象

import socket
try:
    response = urlopen('https://www.zhihu.com', timeout=0.01)
except URLError as e:
    print(type(e.reason))
    if isinstance(e.reason, socket.timeout):
        print('time out')
<class 'socket.timeout'>
time out

HTTPError

它是URLError的子類,專門用來請求HTTP請求錯誤,包含code, reason和headers三個屬性。

from urllib.request import *
from urllib.error import *
try:
    response = urlopen('https://www.zhihu.com/people/happy233333')
except HTTPError as e:
    print(e.reason)
    print(e.code)
    print(e.headers)
# 先判斷子類error,再判斷父類error,符合包含關係
except URLError as e:
    print(e.reason)
else:
    print('everything ok')
Not Found
404
Server: Tengine
Content-Type: text/plain; charset=utf-8
Content-Length: 9
Connection: close
Date: Mon, 06 Jan 2020 14:38:57 GMT
0: cache-control
0: no-cache, no-store, must-revalidate, private, max-age=0
1: connection
1: close
2: content-length
2: 87
3: content-type
3: application/json
4: date
4: Mon, 06 Jan 2020 14:38:57 GMT
5: expires
5: Thu, 01 Jan 1970 08:00:00 CST
6: pragma
6: no-cache
7: server
7: openresty
8: vary
8: Origin
9: x-backend-response
9: 0.002
10: x-tracing-servicename
10: profile-nweb-go
11: x-tracing-spanname
11: MembersHandler_GET
x-backend-server: heifetz.heifetz.heifetz--951-4de26ba7-7c9d7f9948-hwfqs---10.210.190.133:3000[10.210.190.133:3000]
X-Backend-Response: 0.069
Cache-Control: no-cache, no-store, must-revalidate, private, max-age=0
Pragma: no-cache
Vary: Accept-Encoding
X-SecNG-Response: 0.07099986076355
Set-Cookie: _xsrf=z8mbdVxH34t3v5yVbFyGFtWYMjqAXRJR; path=/; domain=zhihu.com; expires=Fri, 24-Jun-22 14:38:57 GMT
x-lb-timing: 0.071
x-idc-id: 2
x-alicdn-da-ups-status: endOs,0,404
x-cdn-provider: alibaba
x-edge-timing: 0.120
Via: c28.l2cm12-6(80,0), c17.cn1780(120,0)
Timing-Allow-Origin: *
EagleId: 78f02c2515783215372268582e


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章