Python requests中Http重定向代码3XX

39 投票
4 回答
53178 浏览
提问于 2025-04-17 20:37

我想获取一个重定向网址的HTTP状态码,特别是3XX/302的状态码。但是我得到的却是200状态码。

这是我的代码:

import requests
r = requests.get('http://goo.gl/NZek5')
print r.status_code

我认为这个请求应该返回301或302状态码,因为它是重定向到另一个页面。我试过几个重定向的网址(比如 http://fb.com),但结果还是返回了200状态码。那我该怎么做才能正确获取到重定向的状态码呢?

4 个回答

0

有没有人能提供这个代码的PHP版本?

    r = requests.get(url)
    if len(r.history) < 1:
        print("Status Code: " + str(r.status_code))
    else:
        print("Status Code: 301. Below are the redirects")
        h = r.history
        i = 0
        for resp in h:
            print("  " + str(i) + " - URL " + resp.url + " \n")
            i += 1
    if do_restart:
2

这个解决方案会识别重定向,并显示重定向的历史记录,同时还会处理一些常见的错误。在控制台中,它会要求你输入网址。

import requests

def init():
    console = input("Type the URL: ")
    get_status_code_from_request_url(console)


def get_status_code_from_request_url(url, do_restart=True):
    try:
        r = requests.get(url)
        if len(r.history) < 1:
            print("Status Code: " + str(r.status_code))
        else:
            print("Status Code: 301. Below are the redirects")
            h = r.history
            i = 0
            for resp in h:
                print("  " + str(i) + " - URL " + resp.url + " \n")
                i += 1
        if do_restart:
            init()
    except requests.exceptions.MissingSchema:
        print("You forgot the protocol. http://, https://, ftp://")
    except requests.exceptions.ConnectionError:
        print("Sorry, but I couldn't connect. There was a connection problem.")
    except requests.exceptions.Timeout:
        print("Sorry, but I couldn't connect. I timed out.")
    except requests.exceptions.TooManyRedirects:
        print("There were too many redirects.  I can't count that high.")


init()
11

requests.get 这个函数有一个可选的参数叫 allow_redirects,默认值是 True。如果把 allow_redirects 设置为 False,那么就不会自动跟随重定向了,具体如下:

In [1]: import requests
In [2]: r = requests.get('http://goo.gl/NZek5', allow_redirects=False)
In [3]: print r.status_code
301
79

requests库会自动处理重定向,也就是说如果你请求的地址发生了变化,它会帮你跟着新的地址去获取内容。想了解更多,可以查看重定向和历史记录的相关内容。

如果你不想让requests库处理重定向,可以设置allow_redirects=False。这样的话,你就可以查看重定向的响应,这些信息会在r.history列表中。

示例:

>>> import requests
>>> url = 'https://httpbin.org/redirect-to'
>>> params = {"status_code": 301, "url": "https://stackoverflow.com/q/22150023"}
>>> r = requests.get(url, params=params)
>>> r.history
[<Response [301]>, <Response [302]>]
>>> r.history[0].status_code
301
>>> r.history[0].headers['Location']
'https://stackoverflow.com/q/22150023'
>>> r.url
'https://stackoverflow.com/questions/22150023/http-redirection-code-3xx-in-python-requests'
>>> r = requests.get(url, params=params, allow_redirects=False)
>>> r.status_code
301
>>> r.url
'https://httpbin.org/redirect-to?status_code=301&url=https%3A%2F%2Fstackoverflow.com%2Fq%2F22150023'

所以,如果allow_redirects设置为True,那么重定向会被跟随,最终返回的就是经过重定向后的页面。如果allow_redirects设置为False,那么返回的就是第一次的响应,即使它是一个重定向。

撰写回答