request類的各種ERROR

2021-10-02 02:48:04 字數 3285 閱讀 3997

urlerror有時候也會是物件

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

from urllib.request import

*from urllib.error import

*try

: response = urlopen(

)except urlerror as e:

print

(e.reason)

not found
from urllib.request import

*from urllib.error import

*try

: response = urlopen(

"")except urlerror as e:

print

(e.reason)

[errno 11001] getaddrinfo failed
from urllib.request import

*from urllib.error import

*try

: response = urlopen(

"")except urlerror as e:

print

(e.reason)

[errno 11003] getaddrinfo failed
上面的三個測試,第乙個是訪問存在的知乎**+不存在的部落格名,第二個是訪問不存在的**。第三個是訪問長城之外的**。

import socket

try:

response = urlopen(

'', timeout=

0.01

)except urlerror as e:

print

(type

(e.reason))if

isinstance

(e.reason, socket.timeout)

:print

('time out'

)

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

# 先判斷子類error,再判斷父類error,符合包含關係

except urlerror as e:

print

(e.reason)

else

:print

('everything ok'

)

not found

404server: 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

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

request 獲取各種路徑

從request獲取各種路徑總結 request.getrealpath url 虛擬目錄對映為實際目錄 request.getrealpath 網頁所在的目錄 request.getrealpath 網頁所在目錄的上一層目錄 request.getcontextpath 應用的web目錄的名稱 如...

request 獲取各種路徑

從request獲取各種路徑總結 request.getrealpath url 虛擬目錄對映為實際目錄 request.getrealpath 網頁所在的目錄 request.getrealpath 網頁所在目錄的上一層目錄 request.getcontextpath 應用的web目錄的名稱 如...

request獲取各種路徑

從request獲取各種路徑總結 request.getrealpath url 虛擬目錄對映為實際目錄 request.getrealpath 網頁所在的目錄 request.getrealpath 網頁所在目錄的上一層目錄 request.getcontextpath 應用的web目錄的名稱 如...