🚀 We are hiring! See open positions

How to fix Python requests TooManyRedirects error?

by scrapecrow Dec 19, 2022

TooManyRedirects error can be seen when using Python requests module to scrape websites with incorrectly configured redirects:

import requests

requests.get("https://httpbin.dev/redirect/31")  # default redirect limit is 30
# will raise:
# TooManyRedirects(requests.exceptions.TooManyRedirects: Exceeded 30 redirects.

# we can set max redirects using requests.Session:
session = requests.Session()
session.max_redirects = 2
session.get("https://httpbin.dev/redirect/3")

When web scraping, this usually means one of 3 things:

  • The website is incorrectly configured.
  • Our requests are missing important details like headers or cookies.
  • The scraper is purposefully redirected in a loop to prevent scraping (i.e. blocking).

To handle ToomanyRedirects exception we should disable automatic redirects and handle them manually:

import requests

session = requests.Session()
response = session.get("https://httpbin.dev/redirect/3", allow_redirects=False)
redirect_url = response.headers['Location']
# now we can manually inspect and fix the redirect url if necessary and then follow it:
response2 = session.get(redirect_url, allow_redirects=False)

Related Articles

How to Scrape AutoScout24

Learn how to scrape AutoScout24 for car listings, prices, specifications, and detailed vehicle information using Python. Complete guide with code examples and anti-blocking techniques.

PYTHON
SCRAPEGUIDE
BEAUTIFULSOUP
REQUESTS
How to Scrape AutoScout24

How to Scrape Ticketmaster Event Data

Learn how to scrape Ticketmaster for event data including concerts, venues, dates, and ticket information using Python. Complete guide with code examples and anti-blocking techniques.

PYTHON
SCRAPEGUIDE
BEAUTIFULSOUP
REQUESTS
How to Scrape Ticketmaster Event Data

How to Scrape Mouser.com

Learn how to scrape Mouser.com electronic component data including prices, specifications, and inventory using Python. Complete guide with code examples and anti-blocking techniques.

PYTHON
SCRAPEGUIDE
BEAUTIFULSOUP
REQUESTS
How to Scrape Mouser.com

How to Scrape Zoro.com

Learn how to scrape Zoro.com product data including prices, specifications, and inventory using Python. Complete guide with code examples and anti-blocking techniques.

PYTHON
SCRAPEGUIDE
BEAUTIFULSOUP
REQUESTS
How to Scrape Zoro.com

Guide to Python requests POST method

Discover how to use Python's requests library for POST requests, including JSON, form data, and file uploads, along with response handling tips.

PYTHON
REQUESTS
HTTP
Guide to Python requests POST method

Guide to Python Requests Headers

Our guide to request headers for Python requests library. How to configure and what do they mean.

PYTHON
REQUESTS
HTTP
Guide to Python Requests Headers