Requests - 处理重定向
本章将介绍 Request 库如何处理 URL 重定向情况。
示例
import 请求 getdata = request.get('http://google.com/') print(getdata.status_code) print(getdata.history)
URL:http://google.com 将使用状态代码 301(永久移动)重定向到 https://www.google.com/。重定向将被保存在历史记录中。
输出
执行上述代码后,我们得到以下结果 −
E:\prequests>python makeRequest.py 200 [<Response [301]>]
您可以使用 allow_redirects = False 停止 URL 重定向。可以在使用的 GET、POST、OPTIONS、PUT、DELETE、PATCH 方法上执行此操作。
示例
以下是相同的示例。
import requests getdata = request.get('http://google.com/', allow_redirects=False) print(getdata.status_code) print(getdata.history) print(getdata.text)
现在,如果您检查输出,重定向将不被允许,并将获得状态代码 301。
输出
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>