English 中文(简体)
Requests - Handling Redirection
  • 时间:2024-09-17

Requests - Handpng Redirection


Previous Page Next Page  

This chapter will take a look at how the Request pbrary handles the url redirection case.

Example


import requests
getdata = requests.get( http://google.com/ )
print(getdata.status_code)
print(getdata.history)    

The url: http://google.com will be redirected using status code 301(Moved Permanently) to https://www.google.com/. The redirection will be saved in the history.

Output

When the above code is executed, we get the following result −


E:prequests>python makeRequest.py
200
[<Response [301]>]

You can stop redirection of a URL using allow_redirects = False. It can be done on GET, POST, OPTIONS, PUT, DELETE, PATCH methods used.

Example

Here is an example on the same.


import requests
getdata = requests.get( http://google.com/ , allow_redirects=False)
print(getdata.status_code)
print(getdata.history)
print(getdata.text)    

Now if you check the output, the redirection will not be allowed and will get a status code of 301.

Output


E:prequests>python makeRequest.py
301
[]
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
Advertisements