Pythonリクエストライブラリが新しいURLをリダイレクトする


95

私はPythonリクエストのドキュメントを調べてきましたが、達成しようとしている機能を確認できません。

私のスクリプトでは、設定していますallow_redirects=True

ページが別のURLにリダイレクトされているかどうかを知りたい。

たとえば、開始URLが次の場合: www.google.com/redirect

そして最終的なURLは www.google.co.uk/redirected

どうすればそのURLを取得できますか?


対処については、この回答を チェックしてくださいurllib2
horcrux

回答:


156

リクエスト履歴を探しています。

この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

67

これは少し異なる質問への回答ですが、私はこれに悩まされたので、他の誰かに役立つと思います。

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

ありがとうございます。これにより、URL参照スクリプト(数千のURLが含まれていました)が数秒高速化されました。
ahinkle 2017年

何が起こっているのか知っていr.nextますか?PreparedRequestリダイレクトURLへの
ポイント


32

私はrequests.getの代わりにrequests.headがURLリダイレクトを処理するときに呼び出す方が安全だと思いますここで githubの問題を確認してください

r = requests.head(url, allow_redirects=True)
print(r.url)

1
これは受け入れられる答えになるはずです。短くて甘い。
Volatil3

5
@ Volatil3:すべてのサーバーがGETと同じ方法でHEADリクエストに応答するわけではありません。
Blender 2017

9

python3.5の場合、次のコードを使用できます。

import urllib.request
res = urllib.request.urlopen(starturl)
finalurl = res.geturl()
print(finalurl)

これはPython 3.5の正解です。見つけるのに少し時間がかかりました。ありがとう
jjj
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.