想在Python中创建一个URL缩短器吗?不用再找了。浏览和分享长的URL是一种痛苦。这么长的URL背后的原因是一个链接中的跟踪器的数量,加载的内容(多个目录)的重型网站,等等。我们都为此使用了URL缩短器,将长的URL缩短为几个字符,这使得它们更容易分享和浏览,而且看起来也很干净和优雅。
但你有没有想过自己编写一个URL缩短器的代码?在本教程中,我们将以非常简单的步骤解释在Python中编码一个URL缩短器的过程。
有很多不同的方法可以缩短URL,其中大部分需要API,你需要坚持只使用一种缩短的URL,例如bitly、tinyurl等等。
URL缩短器的代码
在本教程中,你将了解到一个python包,与传统方法相比,它使缩短URL变得非常容易。
1.安装该模块
首先,我们需要安装所需的模块,这将大大减轻我们编码URL缩短器的工作。我们首先使用pip软件包管理器安装python库。
Pyshorteners 是Python库,用于包装和消费最常用的URL缩短器API。
pip install pyshorteners
2.导入、输入和初始化
在一个Python文件中,我们首先要导入所需的模块。
import pyshorteners
在这一点上我们接受用户的输入,我们可以在代码的后面完成输入部分,但这将让我们改变代码的基本/永久结构,我们将为每个URL缩短器的API改变结构。
long_url = input("Enter the URL to shorten: ")
现在我们初始化pyshortener库的类对象,开始缩短我们的URL。
type_tiny = pyshorteners.Shortener()
3.缩短URL - Tinyurl
现在,由于我们已经初始化了我们的库,我们可以开始缩短URL了。
如果PDF不在python脚本的同一目录中,你需要把名字和PDF的位置一起传给它。
short_url = type_tiny.tinyurl.short(long_url)
print("The Shortened URL is: " + short_url)
在输出中,我们得到缩短的URL,其形式为--"tinyurl.com/mbq3m"。而**T…** 是因为URL缩短器包--Pyshortener默认使用Tinyurl API。
使用TinyURL服务缩短的最终代码------
import pyshorteners
long_url = input("Enter the URL to shorten: ")
#TinyURL shortener service
type_tiny = pyshorteners.Shortener()
short_url = type_tiny.tinyurl.short(long_url)
print("The Shortened URL is: " + short_url)
但我们可以改变它,这就是我们在本教程中要进一步学习的内容。
4.缩短URL - Bitly
Bitly是迄今为止最流行和最广泛使用的URL缩短器服务。在这里,使用我们的代码,我们现在将使用它的API生成缩短的URL,它是由Pyshortener库包裹的。
使用上述同样的方法,只是现在我们需要在Shortener方法中传递我们的API密钥,如图所示。
type_bitly = pyshorteners.Shortener(api_key='01b6c587cskek4kdfijsjce4cf27ce2')
short_url = type_bitly.bitly.short('https://www.google.com')
你可能想知道,你现在从哪里得到API密钥,所以去Bitly网站>创建一个账户>然后去设置>API(开发者)选项。该页面看起来像这样。
输入你的密码生成你的账户的访问令牌,然后复制令牌在代码中使用即可。
使用Bitly API用Python缩短URL的最终代码
import pyshorteners
long_url = input("Enter the URL to shorten: ")
#Bitly shortener service
type_bitly = pyshorteners.Shortener(api_key='01b6c587cskek4kdfijsjce4cf27ce2')
short_url = type_bitly.bitly.short('https://www.google.com')
print("The Shortened URL is: " + short_url)
Bitly服务还提供了更多的功能,如URL扩展、获得缩短后的URL的总点击量等。
expand_url = type_bitly.bitly.expand('https://bit.ly/TEST')
print (expand_url) # gives the url in expand or original form
count = type_bitly.bitly.total_clicks('https://bit.ly/TEST') #gives total no. of clicks.
使用API密钥有助于我们以更好的方式管理我们的链接,因为我们现在可以在该特定缩短服务(网站)仪表板的账户部分检查我们链接的所有细节和性能。
5.使用其他服务缩短URL
各种服务的示例代码会是这样的。
import pyshorteners
s = pyshorteners.Shortener()
#Chilp.it
s.chilpit.short('http://www.google.com') # gives output -> 'http://chilp.it/TEST'
s.chilpit.expand('http://chilp.it/TEST')
# Adf.ly
s = pyshorteners.Shortener(api_key='YOUR_KEY', user_id='USER_ID', domain='test.us', group_id=12, type='int')
s.adfly.short('http://www.google.com') # gives output -> 'http://test.us/TEST'
#Git.io
s = pyshorteners.Shortener(code='12345')
s.gitio.short('https://github.com/TEST') # gives output -> 'https://git.io/12345'
s.gitio.expand('https://git.io/12345')
#and many more services are supported
总结
本教程到此为止。希望你已经了解了URL的缩短,以及如何使用Python创建一个URL缩短器,并使用多个缩短服务提供者。