에러
에러 예시
import requests
url = 'https://httpbin.dev/redirect/31'
with requests.get(url, allow_redirects = True) as r:
print(r.status_code)
r.raise_for_status()
>> Traceback (most recent call last):
File "c:\seolpyo\example.py", line 3, in <module>
with requests.get(url, allow_redirects = True) as r:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\seolpyo\python\Lib\site-packages\requests\api.py", line 73, in get
return request("get", url, params=params, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\seolpyo\python\Lib\site-packages\requests\api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\seolpyo\python\Lib\site-packages\requests\sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\seolpyo\python\Lib\site-packages\requests\sessions.py", line 725, in send
history = [resp for resp in gen]
^^^^^^^^^^^^^^^^^^^^^^
File "C:\seolpyo\python\Lib\site-packages\requests\sessions.py", line 725, in <listcomp>
history = [resp for resp in gen]
^^^^^^^^^^^^^^^^^^^^^^
File "C:\seolpyo\python\Lib\site-packages\requests\sessions.py", line 191, in resolve_redirects
raise TooManyRedirects( requests.exceptions.TooManyRedirects: Exceeded 30 redirects.
해결방법
- requests의 세션 객체를 이용하여 최대 redirect 횟수를 수정하거나,
- 리다이렉트되는 최종 url을 알아내어 응답 요청을 보낸다.
설명
파이썬의 requests 모듈은 최대 redircet 횟수를 30회로 제한하고 있다.
이 redirect 횟수를 수정하려면 requests.sesseion 명령으로 Session(세션) 객체를 사용해야하며, 세션의 max_redirects 변수값을 수정하는 것으로 문제 해결이 가능하다.
만약 세션을 사용하고 싶지 않다면 url 접속시 최종 접속되는 페이지의 url을 알아내어 그 url에 응답 요청을 보내면 된다.
import requests
url = 'https://httpbin.dev/redirect/31'
# https://white.seolpyo.com/
with requests.session() as s:
s.max_redirects = 32
r = s.get(url)
print(r.status_code)
r.raise_for_status()
print(r.content)
>> 200
b'{\n "args": {},\n "headers": {\n "Accept": [\n "*/*"\n ],\n "Accept-Encoding": [\n "gzip, deflate, br, zstd"\n ],\n "Host": [\n "httpbin.dev"\n ],\n "User-Agent": [\n "python-requests/2.31.0"\n ]\n },\n "origin": "180.66.204.185",\n "url": "https://httpbin.dev/get"\n}\n'