回答:
リクエスト履歴を探しています。
このresponse.history
属性は、最終的なURLにつながった応答のリストであり、にありますresponse.url
。
response = requests.get(someurl)
if response.history:
print("Request was redirected")
for resp in response.history:
print(resp.status_code, resp.url)
print("Final destination:")
print(response.status_code, response.url)
else:
print("Request was not redirected")
デモ:
>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
... print(resp.status_code, resp.url)
...
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get
これは少し異なる質問への回答ですが、私はこれに悩まされたので、他の誰かに役立つと思います。
allow_redirects=False
チェーンをたどるのではなく、最初のリダイレクトオブジェクトを使用して直接取得する場合、リダイレクトの場所を302レスポンスオブジェクトから直接取得するだけでr.url
は機能しません。代わりに、それは「Location」ヘッダーです。
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code # 302
r.url # http://github.com, not https.
r.headers['Location'] # https://github.com/ -- the redirect destination
r.next
ますか?PreparedRequest
リダイレクトURLへの
ドキュメントにはこの宣伝文句がありますhttps://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history
import requests
r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for
urllib2