20

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

附加说明:

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

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

4

10 回答 10

40

向 URL 发送 HTTP HEAD 请求并查看响应代码。如果代码是 30x,请查看Location标头以获取未缩短的 URL。否则,如果code是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
于 2010-11-17T03:20:28.380 回答
31

使用请求:

import requests

session = requests.Session()  # so connections are recycled
resp = session.head(url, allow_redirects=True)
print(resp.url)
于 2015-03-07T18:00:10.040 回答
5

Unshorten.me有一个 API,可让您发送 JSON 或 XML 请求并获取返回的完整 URL。

于 2010-11-17T03:00:04.943 回答
4

打开网址,看看它解析为:

>>> import urllib2
>>> a = urllib2.urlopen('http://bit.ly/cXEInp')
>>> print a.url
http://www.flickr.com/photos/26432908@N00/346615997/sizes/l/
>>> a = urllib2.urlopen('http://google.com')
>>> print a.url
http://www.google.com/
于 2010-11-17T03:19:40.717 回答
4

要取消简短,您可以使用请求。这是一个对我有用的简单解决方案。

import requests
url = "http://foo.com"

site = requests.get(url)
print(site.url)
于 2017-05-01T00:03:55.747 回答
3

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

from unshortenit import UnshortenIt
unshortener = UnshortenIt()
uri = unshortener.unshorten('https://href.li/?https://example.com')
于 2020-05-04T07:51:11.750 回答
1

http://github.com/stef/urlclean

sudo pip install urlclean
urlclean.unshorten(url)
于 2013-07-12T13:34:57.917 回答
1

这里的 src 代码几乎考虑了有用的极端情况:

  • 设置自定义超时。
  • 设置自定义用户代理。
  • 检查我们是否必须使用 http 或 https 连接。
  • 递归解析输入 url 并防止在循环中结束。

src 代码在 github @ https://github.com/amirkrifa/UnShortenUrl

欢迎评论...

import logging
logging.basicConfig(level=logging.DEBUG)

TIMEOUT = 10
class UnShortenUrl:
    def process(self, url, previous_url=None):
        logging.info('Init url: %s'%url)
        import urlparse
        import httplib
        try:
            parsed = urlparse.urlparse(url)
            if parsed.scheme == 'https':
                h = httplib.HTTPSConnection(parsed.netloc, timeout=TIMEOUT)
            else:
                h = httplib.HTTPConnection(parsed.netloc, timeout=TIMEOUT)
            resource = parsed.path
            if parsed.query != "": 
                resource += "?" + parsed.query
            try:
                h.request('HEAD', 
                          resource, 
                          headers={'User-Agent': 'curl/7.38.0'}
                                   }
                          )
                response = h.getresponse()
            except:
                import traceback
                traceback.print_exec()
                return url

            logging.info('Response status: %d'%response.status)
            if response.status/100 == 3 and response.getheader('Location'):
                red_url = response.getheader('Location')
                logging.info('Red, previous: %s, %s'%(red_url, previous_url))
                if red_url == previous_url:
                    return red_url
                return self.process(red_url, previous_url=url) 
            else:
                return url 
        except:
            import traceback
            traceback.print_exc()
            return None
于 2015-07-15T21:22:15.280 回答
1

您可以使用geturl()

from urllib.request import urlopen
url = "bit.ly/silly"
unshortened_url = urlopen(url).geturl()
print(unshortened_url)
# google.com
于 2020-06-17T07:23:42.160 回答
0

这是非常简单的任务,您只需要添加 4 行代码即可:)

import requests
url = input('Enter url : ')
site = requests.get(url)
print(site.url)

只需运行此代码,您将成功取消短网址。

于 2021-09-03T17:14:06.680 回答