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
'program story' 카테고리의 다른 글
Android : 대화 상자의 EditText가 소프트 키보드를 표시하지 않습니다. (0) | 2020.10.11 |
---|---|
OFFSET / FETCH NEXT에서 총 행 수 가져 오기 (0) | 2020.10.11 |
선택된 상태의 Android ImageButton? (0) | 2020.10.11 |
현재 PowerShell 프로세스가 32 비트인지 64 비트인지 확인합니까? (0) | 2020.10.11 |
Java 정적 호출은 비 정적 호출보다 비용이 많이 듭니까? (0) | 2020.10.11 |