如何取消缩短网址? [英] How can I unshorten a URL?

查看:94
本文介绍了如何取消缩短网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够采用缩短或未缩短的 URL 并返回其未缩短的形式.我怎样才能制作一个 python 程序来做到这一点?

I want to be able to take a shortened or non-shortened URL and return its un-shortened form. How can I make a python program to do this?

补充说明:

  • 情况 1:缩短 --> 未缩短
  • 情况 2:未缩短 --> 未缩短

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

e.g. bit.ly/silly in the input array should be google.com in the output array
e.g. google.com in the input array should be google.com in the output array

推荐答案

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

Send an HTTP HEAD request to the URL and look at the response code. If the code is 30x, look at the Location header to get the unshortened URL. Otherwise, if the code is 20x, then the URL is not redirected; you probably also want to handle error codes (4xx and 5xx) in some fashion. For example:

# 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

这篇关于如何取消缩短网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆