How can I un-shorten a URL using python?

后端 未结 4 1578
孤城傲影
孤城傲影 2020-12-08 12:22

I have seen this thread already - How can I unshorten a URL?

My issue with the resolved answer (that is using the unshort.me API) is that I am focusing on unshorteni

4条回答
  •  感动是毒
    2020-12-08 13:08

    Use the best rated answer (not the accepted answer) in that question:

    # 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
    

提交回复
热议问题