Skip to main content
 首页 » 编程设计

python之当最终网址为 https 时,如何使用 python 取消缩短(解析)网址

2025年05月04日9sharpest

当最终网址为 https 时,我希望在 python 中取消缩短(解析)网址。我看到了这个问题:How can I un-shorten a URL using python? (以及类似的其他),但是正如对已接受答案的评论中指出的那样,此解决方案仅在 url 未重定向到 https 时才有效。

作为引用,该问题中的代码(重定向到 http url 时工作正常)是:

# This is for Py2k.  For Py3k, use http.client and urllib.parse instead, and 
# use // instead of / for the division 
import httplib 
import urlparse 
 
def unshorten_url(url): 
    parsed = urlparse.urlparse(url) 
    h = httplib.HTTPConnection(parsed.netloc) 
    resource = parsed.path 
    if parsed.query != "": 
        resource += "?" + parsed.query 
    h.request('HEAD', resource ) 
    response = h.getresponse() 
    if response.status/100 == 3 and response.getheader('Location'): 
        return unshorten_url(response.getheader('Location')) # changed to     process chains of short urls 
    else: 
        return url 

(注意 - 出于明显的带宽原因,我希望通过仅请求文件头 [即像上面的 http-only 版本] 而不是通过请求整个页面的内容来实现)

请您参考如下方法:

如果 parsed.scheme 是 https,您可以从 url 获取方案,然后使用 HTTPSConnection .
您也可以使用请求库来非常简单地完成此操作。

>>> import requests 
>>> r = requests.head('http://bit.ly/IFHzvO', allow_redirects=True) 
>>> print(r.url) 
https://www.google.com