python requests redirect

Python Requests Redirect

Python Requests is a popular library used for making HTTP requests in Python. It provides several features, including the ability to handle redirects. In this article, we'll discuss how to use the redirect feature in Python Requests.

Using Redirect in Python Requests

When a URL is requested using Python Requests, it may return a redirect status code (e.g., 301, 302, 307). By default, Python Requests will follow the redirect and return the final response. However, you can also configure it to not follow the redirect or to manually handle the redirect.

To disable automatic redirect following, you can set the allow_redirects parameter to False:


import requests

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

print(response.status_code)
    

This will return the initial redirect status code (e.g., 301, 302, 307) instead of following the redirect.

To manually handle redirects, you can check the status_code of the response and use the headers to get the new location:


import requests

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

if response.status_code == 301:
    new_url = response.headers['Location']
    response = requests.get(new_url)

print(response.status_code)
    

This will check if the response status code is a redirect (e.g., 301, 302, 307), get the new location from the headers, and make a new request to the redirected URL.

Overall, Python Requests provides a convenient way to handle redirects when making HTTP requests. Whether you need to disable automatic following or manually handle the redirect, Python Requests has you covered.