First, you need to use the API to generate a shortened URL Get the API key. Please create a Token on the site of the following URL. https://bitly.com/a/oauth_apps
If you get it there, you can put it in the variable access_token in the main function (```if name == "main" `` `) of the code below. After that, specify the URL to be shortened with the command line argument, and you're done.
Execution example
von:~ von$ python /Users/von/Desktop/URL_Shortening.py https://www.youtube.com/
Output example
http://bit.ly/24eSWTH
URL_Shortening.py
def GET_Url(access_token, longUrl):
import urllib, urllib2, json
url = 'https://api-ssl.bitly.com/v3/shorten'
values = {
"access_token": access_token,
"longUrl": longUrl
}
req = urllib2.Request(url, urllib.urlencode(values))
result = json.loads(urllib2.urlopen(req).read())
return result["data"]["url"]
if __name__ == "__main__":
import sys
access_token = "XXXXXXXXXXXXXXXXXXXXXXXXXXX"
print GET_Url(access_token, sys.argv[1])
Recommended Posts