Python:如何判断链接是否重定向到另一个页面?

4

我有一份URL列表,但其中许多已过期,会重定向到其主页或域中的其他页面。我想从我的列表中过滤掉这些URL。如何使用requests来过滤掉不在原地打开的URL?

2个回答

7

您应该检查响应历史记录注意:并非所有站点都使用重定向来显示其他页面。

>>> r = requests.head('http://github.com', allow_redirects=True)
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]

您还可以防止重定向并检查响应的status_code,请参见此示例

>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]

0
这是我在项目中使用的方法:http://www.elfinite.com/
def get_last_redirected_url(self, url):
    """
    """
    try:
        response = requests.get(url)
        if response.history:
            # Request was redirected
            return response.url
        else:
            # Request was not redirected"
            return url
    except Exception as e:
        return False
        pass

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接