如何使用Bilty API缩短URL列表?

时间:2013-09-17 08:43:56

标签: url url-shortener bit.ly short-url

我在Bitly有一个帐户,可以个性化我的网址缩短。如何使用API​​登录并缩短网址列表?

1 个答案:

答案 0 :(得分:1)

这是我使用python requests

在python中的解决方案
    import base64 
    import requests
    import json 

    credentials = 'USERNAME:PASSWORD'

    urls = ['www.google.com', 'www.google.co.uk', 'www.google.fr']

    def getShortURLs(urls):
        token = auth()
        return shortenURLs(token, urls)

    def auth():
        base_auth = "https://api-ssl.bitly.com/oauth/access_token"
        headers = {'Authorization': 'Basic ' + base64.b64encode(credentials)}
        resp = requests.post(base_auth, headers=headers)
        return resp.content

    def shortenURLs(token, long_urls):
        base = 'https://api-ssl.bitly.com/v3/shorten'
        short_urls = []
        for long_url in long_urls:
            if long_url:
                params = {'access_token':token, 'longUrl' : 'https://' + long_url}
                response = requests.get(base, params=params)
                r = json.loads(response.content)
                short_urls.append(r['data']['url'])
        return short_urls