program story

Python 요청 라이브러리 리디렉션 새 URL

inputbox 2020. 10. 11. 10:31
반응형

Python 요청 라이브러리 리디렉션 새 URL


Python Requests 문서를 살펴 보았지만 달성하려는 기능에 대한 기능을 볼 수 없습니다.

내 스크립트에서 allow_redirects=True.

페이지가 다른 것으로 리디렉션되었는지 여부, 새 URL이 무엇인지 알고 싶습니다.

예를 들어 시작 URL이 다음과 같으면 www.google.com/redirect

그리고 최종 URL은 www.google.co.uk/redirected

그 URL을 어떻게 얻습니까?


요청 내역을 찾고 있습니다 .

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체인을 r.url따르지 않고 첫 번째 리디렉션 개체 를 사용 하고 직접 가져오고 싶고 302 응답 개체에서 직접 리디렉션 위치를 가져 오려면 작동하지 않습니다. 대신 "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

문서에는 http://docs.python-requests.org/en/latest/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 

url 리디렉션을 처리 할 때 requests.get 대신 requests.head 가 호출하는 것이 더 안전 하다고 생각 합니다 . 여기 에서 github 문제를 확인 하십시오 .

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

python3.5의 경우 다음 코드를 사용할 수 있습니다.

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

참고 URL : https://stackoverflow.com/questions/20475552/python-requests-library-redirect-new-url

반응형