【问题标题】:url shortening in pythonpython中的url缩短
【发布时间】:2020-05-31 05:43:36
【问题描述】:

我正在尝试找到使用 python 3 缩短 URL 的最简单方法。到目前为止,我看到的库已经过时并且不再维护。人们会看到这些 URL,所以我想使用一些值得信赖的东西,比如 tinyurl 或 bit.ly 或 goog.gl

给定一个 URL,我如何将它传递给一个可以缩短它的函数?

2020 年以编程方式缩短 URL 的最佳方法是什么?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    对于 bit.ly,您可以使用他们的 API,该 API 记录在 here。如果它是一个简单的应用程序,您可能应该从通用访问令牌开始(获取一个here

    获得访问令牌后,您可以发布请求:

    • 方法:POST
    • 网址:https://api-ssl.bitly.com/v4/shorten
    • 标题:

      Authorization: Bearer TOKEN_GOES_HERE```
      
    • 正文:

        "domain": "bit.ly",
        "long_url": "https://www.my-url.com"
      }```
      

    回复是:

    {
    "created_at": "2020-05-31T06:20:30+0000",
    "id": "...",
    "link": "<bit-ly link comes here",
    "custom_bitlinks": [],
    "long_url": "https://www.my-url.com/",
    ... some other stuff. 
    

    在python中,它看起来像:

    headers = {
        "content-type": "application/json", 
        "Authorization": "Bearer <TOKEN_GOES_HERE"
    }
    
    body = json.dumps({
      "domain": "bit.ly",
      "long_url": "https://www.my-url.com"
    })
    
    URL = "https://api-ssl.bitly.com/v4/shorten"
    res = requests.post(url = URL, data = body, headers = headers)
    

    【讨论】:

      【解决方案2】:

      您可以参考 bit.ly 获取 sortener url,为此您需要在 bitly 上创建您的帐户,您生成 access_token 需要将您的帐户与您的代码集成并对 url 进行排序,并将该 url 存储到你的小帐户。
      pip install bitlyshortener

      from bitlyshortener import Shortener
      # get access token from bitly
      tokens_pool = ['your_bitly_access_token']
      shortener = Shortener(tokens=tokens_pool, max_cache_size=128)
      # get url into list
      urls = []
      url = input("Enter url: ")
      urls.append(url)
      
      # shorten using bitly
      short_urls = shortener.shorten_urls_to_dict(url)
      print("short urls: ", short_urls[url])
      

      【讨论】:

        【解决方案3】:

        试试这个脚本。

        http://code.activestate.com/recipes/576918/

        用法:

        >>> import short_url
        >>> url = short_url.encode_url(12)
        >>> print url
        LhKA
        >>> key = short_url.decode_url(url)
        >>> print key
        12
        

        【讨论】:

          猜你喜欢
          • 2020-06-10
          • 2020-03-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多