requests为您
处理重定向,请参阅重定向和历史记录。
设置
allow_redirects=False是否不想
requests处理重定向,或者可以检查
r.historylist中包含的重定向响应。
演示:
>>> import requests>>> url = 'https://httpbin.org/redirect-to'>>> params = {"status_pre": 301, "url": "https://stackoverflow.com/q/22150023"}>>> r = requests.get(url, params=params)>>> r.history[<Response [301]>, <Response [302]>]>>> r.history[0].status_pre301>>> r.history[0].headers['Location']'https://stackoverflow.com/q/22150023'>>> r.url'https://stackoverflow.com/questions/22150023/http-redirection-pre-3xx-in-python-requests'>>> r = requests.get(url, params=params, allow_redirects=False)>>> r.status_pre301>>> r.url'https://httpbin.org/redirect-to?status_pre=301&url=https%3A%2F%2Fstackoverflow.com%2Fq%2F22150023'因此,如果
allow_redirects为
True,则遵循重定向,返回的最终响应是跟随重定向后的最终页面。如果
allow_redirects为
False,则返回第一个响应,即使它是重定向的。



