我怎样才能取消URL?

And*_*rew 15 python url url-shortener

我希望能够获取缩短或未缩短的URL并返回其未缩短的表单.我怎么能做一个python程序来做到这一点?

额外澄清:

  • 案例1:缩短 - >未缩短
  • 案例2:未经训练 - >未经训练

例如bit.ly/silly,在输入数组中应该google.com在输出数组中,
例如google.com在输入数组中应该google.com在输出数组中

Ada*_*eld 35

向URL发送HTTP HEAD请求并查看响应代码.如果代码是30x,请查看Location标题以获取未缩减的URL.否则,如果代码是20x,则不会重定向URL; 您可能还想以某种方式处理错误代码(4xx和5xx).例如:

# 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)
    h.request('HEAD', parsed.path)
    response = h.getresponse()
    if response.status/100 == 3 and response.getheader('Location'):
        return response.getheader('Location')
    else:
        return url
Run Code Online (Sandbox Code Playgroud)

  • 如果你想获得实际的URL,请在使用上面的代码时注意不要递归地取消.试试`http:// t.co/hAplNMmSTg`.你需要做`return unshorten_url(response.getheader('Location'))`用于递归. (5认同)

Ger*_*inZ 22

使用请求:

import requests

session = requests.Session()  # so connections are recycled
resp = session.head(url, allow_redirects=True)
print(resp.url)
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个解决方案,它会自动遵循多个重定向 (3认同)

use*_*049 5

Unshorten.me有一个api,允许您发送JSON或XML请求并返回完整的URL.


fma*_*arm 5

如果您使用的是 Python 3.5+,您可以使用Unshortenit模块,这使这变得非常简单:

from unshortenit import UnshortenIt
unshortener = UnshortenIt()
uri = unshortener.unshorten('https://href.li/?https://example.com')
Run Code Online (Sandbox Code Playgroud)