請求 - 處理重定向



本章將探討 Request 庫如何處理 url 重定向案例。

示例

import requests
getdata = requests.get('http://google.com/')
print(getdata.status_code)
print(getdata.history)    

url:http://google.com將使用狀態程式碼 301(永久移動)重定向到https://www.google.com/。重定向將儲存到歷史記錄中。

輸出

在執行以上程式碼後,我們將得到以下結果 -

E:\prequests>python makeRequest.py
200
[<Response [301]>]

你可以使用 allow_redirects = False 停止 URL 的重定向。這可以在 GET、POST、OPTIONS、PUT、DELETE、PATCH 方法中使用。

示例

以下是相同主題的一個示例。

import requests
getdata = requests.get('http://google.com/', allow_redirects=False)
print(getdata.status_code)
print(getdata.history)
print(getdata.text)    

如果你檢查輸出,將不會允許重定向並且將得到狀態程式碼 301。

輸出

E:\prequests>python makeRequest.py
301
[]
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
廣告