Note: this is an untested approach, but here for illustration/inspiration
I don't believe the requests
library has any way of doing this automagically for you.
So, I propose you:
- Disable redirects (set
allow_redirects=False
on your request)
- Inspect the
Response
object to see if it was a redirect response (there are helper @property
available!)
- Parse the redirect URL and make your decision as to whether to follow that redirect or not
Something like:
import requests
from urllib3.util import parse_url
intial_url = "http://192.168.1.1/"
response = requests.get(url=intial_url, allow_redirects=False)
# <https://github.com/psf/requests/blob/6e5b15d542a4e85945fd72066bb6cecbc3a82191/requests/models.py##L770-L775>
if response.is_redirect:
redirect_url = response.headers["location"]
if parse_url(intial_url).host == parse_url(redirect_url).host:
# follow redirect?
request.get(url=redirect_url, allow_redirects=False)
Obviously there's more to do (e.g. recursively follow redirects) but thought it might be useful anyhow