Requests-handling-redirection
提供:Dev Guides
リクエスト-リダイレクトの処理
この章では、リクエストライブラリが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>