How to fix TooManyRedirects error in Python requests?

TooManyRedirects error occurs when the request redirects continuously. By default, requests has a limit of 30 redirects. If it encounters more than 30 redirects in a row then it throws this error.

Firstly, you should make sure that the website is not buggy. There aren't a lot of scenarios where more than 30 redirects make sense. Maybe the website is detecting your requests as automated and intentionally sending you in a redirection loop.

If you are sure the website is not buggy then you can increase the redirect limit by using the Sessions object and increasing the max_redirects property like this:

import requests

session = requests.Session()

# Increase the redirect count to 40
session.max_redirects = 40
session.get("http://httpbin.org/redirect/39")

Related Requests web scraping questions: