Python Requests - Handling Redirection5 Jan 2025 | 4 min read The requests library in Python is a powerful and popular tool for making HTTP requests. One of its useful features is handling redirection automatically. Redirection is a common occurrence on the web, where a server responds to a client's request by directing it to another URL. This can be happen for different reasons, such as URL restructuring, load balancing, or content relocation. Understanding how to handle these redirects using the requests library is essential for building robust and efficient web scraping or web interaction tools. Understanding HTTP RedirectionBefore diving into the specifics of handling redirection with the requests library, it's important to understand the basics of HTTP redirection. HTTP redirection is indicated by 3xx status codes in the server's response. Common 3xx status codes include:
When a client receives one of these status codes, it needs to follow the redirect to the new URL provided in the Location header of the response. Handling Redirection with requestsThe requests library simplifies handling redirection. By default, it follows redirects automatically. Here's a basic example of how it works: Output: https://github.com 200 In this example, if you visit http://github.com, you'll notice it redirects to https://github.com. The requests library follows this redirect automatically, and the final URL is printed out. Controlling Redirection BehaviorWhile the default behavior of following redirects is convenient, there are scenarios where you might want more control over the redirection process. The requests library provides several ways to manage this. Disabling Redirection To disable automatic redirection, you can use the allow_redirects parameter: Output: 301 https://github.com/ In this case, requests will not follow the redirect. The response will contain the original status code (e.g., 301) and the Location header with the URL to which the request would have been redirected. Limiting the Number of Redirects By default, requests will follow up to 30 redirects. You can change this limit using a custom session and the max_redirects attribute: Output: http://example.com/ In this example, the session will follow a maximum of 5 redirects. If the redirection chain exceeds the respective desired limit, a TooManyRedirects exception will be raised. Inspecting the Redirection HistoryThe requests library allows you to inspect the history of redirects that occurred during the request. This is available via the history attribute of the response object: Output: [ The history attribute is a list of response objects that were created during the redirection process. You can iterate over this list to see each intermediate step. Practical ApplicationsWeb Scraping When scraping websites, handling redirects is crucial because many sites use redirection to manage their content. For example, a website might redirect users to a mobile version of the site if accessed from a mobile device. Here's how you can handle such scenarios: Output: Redirected History: 301 http://example.com 200 https://www.iana.org/domains/example Example Domain In this example, the script handles redirection automatically and then uses BeautifulSoup to parse the final content. API RequestsSome APIs use redirection to balance load across different servers. When working with such APIs, it's important to handle redirects to ensure that your requests reach the correct server: Output: Request failed with status code: 404 In this case, the script follows redirects to ensure that the API request is completed successfully. ConclusionHandling redirection with the requests library in Python is straightforward thanks to its built-in support for automatic redirection. By understanding the basics of HTTP redirection and using the various features and customization options provided by the requests library, you can effectively manage redirection in your web scraping and web interaction tasks. Whether you need to follow redirects automatically, disable them, limit the number of redirects, or implement custom redirect handling logic, the requests library offers the flexibility and power to meet your needs. |
Disassembler for Python Bytecode
Introduction Python bytecode disassembly is an interesting part of Python programming that permits designers to dig profoundly into the inward operations of their Python code. Bytecode is the low-level, stage free portrayal of Python code that is executed by the Python mediator. While Python designers ordinarily...
13 min read
Default Arguments in Python
Introduction Python has one of the most useful and easiest features, default arguments are used, which is the ability to set initial values for parameters in a function. It simplifies function calling, thus making the code clearer for reading and maintaining. This paper will explain what...
4 min read
Inverse Propensity Weighting in Python with causallib
Introduction to Inverse Propensity Weighting (IPW) Inverse Propensity Weighting (IPW) is a statistical technique utilized in causal derivation and observational examinations to gauge treatment impacts when randomization is not possible or ethical. It's a powerful tool in the weapons store of specialists and information researchers working...
7 min read
CNN Algorithm Code in Python
Convolutional neural network algorithm (CNN) is a deep learning algorithm well-suited for image processing. They are composed of convolutional, pooling, and fully connected layers. Convolutional layers play a vital role in Convolutional Neural Networks (CNNs). These layers employ filters that help extract image features such as...
5 min read
Count Values in Pandas DataFrame
Introduction: Python's Pandas DataFrame is a robust and adaptable data shape for handling and inspecting tabular records. It is a component of the library known as Pandas, that is substantially used for analysis and records manipulation. Similar to a spreadsheets or SQL desk, a DataFrame is conceptualised...
8 min read
How to Open a File in Binary Mode with Python
? In the following tutorial we learn the method of opening a File in Binary Mode using Python. But before we get started, let us briefly discuss about the file handling in Python. File Handling in Python Files in Python are used for reading from and writing to external...
3 min read
Turtle.undo() Function in Python
An Introduction The concept being taught is Turtle graphics from the Python programming language is possibly the best way to teach a beginner programming concept. It is an incredibly easy to use tool to make drawings, animations or even simple games come to life. turtle.undo() - this...
4 min read
What is a Default Value in Python
? Introduction: In this tutorial we are learning the default value in Python. Python allows functions to have default values. The arguments take their default values if you call the function without argument. The Python language has many ways to express syntax and values for function arguments....
7 min read
Debug in Python
An Introduction Debugging is a vital part of the software industry. Writing correct and flawless code as a Python developer implies perfect knowledge in the art of debugging. This is a thorough guide that will show us several ways of debugging, Python tools and ways for...
4 min read
How to Plot Two Histograms Side by Side Using Matplotlib in Python
? Understanding Histograms Histograms are graphical portrayals of the dissemination of mathematical information. They give a visual rundown of the recurrence or thickness of information values inside unambiguous stretches, frequently alluded to as "containers." Histograms are generally utilized in information examination and representation to investigate the fundamental...
9 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India