【问题标题】:How to un-shorten (resolve) a url using python, when final url is https?当最终网址为 https 时,如何使用 python 取消缩短(解析)网址?
【发布时间】:2015-06-08 03:23:56
【问题描述】:

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

作为参考,该问题中的代码(在重定向到 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 版本] 而不是询问整个页面的内容来实现)

【问题讨论】:

    标签: python python-2.7 url-shortener


    【解决方案1】:

    如果parsed.scheme 是https,您可以从url 获取方案,然后使用HTTPSConnection。
    您也可以使用 requests 库非常简单地做到这一点。

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

    【讨论】:

    • 谢谢 - 必须在请求中添加选项“verify=False”,因为在不同 https 域之间重定向时会发生 ssl 错误。 (意识到不验证 ssl 证书的危险)
    猜你喜欢
    • 2019-05-12
    • 2013-10-20
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多