python requests no redirect

Python Requests No Redirect

If you are working with the Python Requests library, you may come across situations where you don't want to follow redirects. In such cases, you can use the allow_redirects parameter and set it to False.

Let me share a personal experience with you. I was working on a web scraping project where I had to fetch some data from a website. However, the website kept redirecting me to another page which was of no use to me. In such a scenario, I had to find a way to prevent these redirects from happening.

The Solution

The solution was quite simple. I had to modify my requests code and set the allow_redirects parameter to False. Here's how I did it:


import requests

response = requests.get('https://example.com', allow_redirects=False)

print(response.status_code)
    

In the code above, I have used the get() method of the Requests module to make a request to the website. The allow_redirects parameter has been set to False, which means that any redirects will not be followed. Finally, I have printed the status code of the response.

You can also set the allow_redirects parameter to True if you want to follow redirects.

Alternative Solution

If you want to prevent redirects globally for all requests, you can use the session() method of the Requests module. Here's an example:


import requests

session = requests.Session()
session.max_redirects = 0

response = session.get('https://example.com')

print(response.status_code)
    

In the code above, I have created a session object using the Session() method. I have then set the max_redirects attribute to 0, which means that any redirects will not be followed. Finally, I have used the get() method of the session object to make a request to the website and printed the status code of the response.

These are the two ways you can prevent redirects while using Python Requests. Choose the one that suits your needs.