I am trying to capture http status code 3XX/302 for a redirection url. But I cannot get it because it gives 200 status code.
Here is the code:
import requests
r = requests.get('http://goo.gl/NZek5')
print r.status_code
I suppose this should issue either 301 or 302 because it redirects to another page. I had tried few redirecting urls (for e.g. http://fb.com ) but again it is issuing the 200. What should be done to capture the redirection code properly?
requests.get
allows for an optional keyword argumentallow_redirects
which defaults toTrue
. Settingallow_redirects
toFalse
will disable automatically following redirects, as follows:requests
handles redirects for you, see redirection and history.Set
allow_redirects=False
if you don't wantrequests
to handle redirections, or you can inspect the redirection responses contained in ther.history
list.Demo:
So if
allow_redirects
isTrue
, the redirects have been followed and the final response returned is the final page after following redirects. Ifallow_redirects
isFalse
, the first response is returned, even if it is a redirect.This solution will identify the redirect and display the history of redirects, and it will handle common errors. This will ask you for your URL in the console.