Python中的URL缩短程序

Python中的URL缩短程序

首先,让我们了解什么是URL缩短器。自互联网诞生以来,用户一直依赖连接作为主要的交通方式。URL缩短是一种Web方法,可以显着缩短统一资源定位器(URL),同时仍然指向所需的网站。这是通过重定向来实现的,重定向指向一个具有长URL的网页。它们可以让用户通过单击URL在几秒钟内从一个网站导航到另一个网站。不幸的是,当添加跟踪参数并且站点结构扩展以处理数百个页面时,连接通常变得冗长且复杂。随着社交媒体的普及,长URL成为一个问题。Twitter曾限制消息最多为140个字符,并计算链接中的每个字符。因此,长URL可能占用您的整个推文。URL缩短程序是对这一共享难题的应对演变而来。

URL缩短器的好处

  • 任何营销计划中都不容忽视内容的重要性。您需要正确的URL来分发该内容。URL缩短程序确保相关信息以不占用社交媒体帖子太多空间的方式传达给目标受众。
  • 通过执行以下操作,使人们更容易分享您的内容:通过使用简单且带有品牌的URL,客户可以了解他们所需了解的有关您的网站的一切。不再需要具有随机字母和数字组合的缩短URL。
  • 使您的URL更具吸引力:从美学的角度来看,较短的URL更具吸引力。尽管可能看起来不重要,但较短的URL可能是鼓励某人点击您的链接的决定性因素。
  • 实现流量监控:Bit.ly包含跟踪监视器,可以随时间跟踪您的推文或帖子的分享活动。

将您自己的自定义域名连接到充当您创建的所有短链接基础的URL缩短程序时,称为自定义或带品牌的URL缩短程序。您可以选择自己的域名,而不是选择像bit.ly或rebrand.ly这样的通用域名。

链接缩短器执行的操作

  • Link Masking : 显然,缩短URL可以隐藏原始的网站地址。这对消费者来说是可怕的,因为它允许垃圾邮件发送者和黑客将危险的链接隐藏起来。幸运的是,Chrome和其他浏览器中的安全功能(你使用Chrome吗?)消除了对恶意链接隐藏的担忧。当你使用适当的链接屏蔽时,你可以将你想要分享的有用信息的URL简化,以传达你社交信息中的重要观点。不要将链接屏蔽与链接伪装混淆,后者涉及向搜索引擎(也称为蜘蛛或机器人)提供虚假信息,同时将人们发送到与伪造材料无关的URL。这是一种黑帽SEO行为,可能导致你的网站被从谷歌的搜索结果中删除。
  • 链接缩短 : 共享一个短小而易记的URL比共享一个包含随机整数的长URL要容易得多,特别是当您在做演示时需要向拥挤的观众大喊哪个URL?当您的名片用完时,在网络活动中您会告诉人们哪个URL?我个人使用的是Derric.link/card。就是这么简单。当您在讨论新鲜想法时,您会想在论坛上使用哪个URL?在公共场合分享链接时,您应该使用链接缩短工具来使其看起来更好,并且可以衡量点击链接的人数。
  • 链接跟踪 : 缩短URL最有力的理由必须是链接跟踪。作为数字营销人员和社交媒体经理,我们必须了解我们的努力的结果。公司ClickMeter必须拥有最先进的技术来追踪从点击到转化的链接。您可以确认有多少真实人点击了链接,而不是多少机器人或蜘蛛点击了它。这为您提供了一个更真实的访问者数和转化率的图片。您还可以获得每日甚至地理位置的详细信息(未显示)。还有很多其他值得探索的事情。
  • 链接跟踪 :缩短URL的最有说服力的理由必须是链接跟踪。作为数字营销人员和社交媒体管理者,我们必须意识到我们努力的结果。我们几乎肯定必须每月提供我们的努力的更新。如果我们不能展示我们的点击次数 – 并且希望能够转化 – 我们的工作安全性就很低。
  • 链接轮播 :您是否想过进行A/B测试,但又不确定如何操作?高级链接功能可以让您将流量划分为50/50 – 或75/25或其他 – 来进行小型着陆页测试。现在,这对于广告来说并不是必需的,因为您可以同时运行两个广告,并且还有其他工具(如Optimizely)可以让您在页面内处理这个问题,而不是在链接内部。但是在链接的分流测试中存在一些选择。您还可以进行竞赛,并将第一次点击定向到“中奖”页面,而其余的点击则定向到“再试一次”页面。
  • 链接交换或更改 :尽管它很简单,但大多数链接缩短提供者都不允许您这样做。您制作了一个缩短链接,并将其分发到12个不同的社交媒体平台,但是您链接指向的页面有一天被删除了。祝您好运去查找和替换所有那些破损的链接。不再需要这样做了。使用Rebrandly,您拥有您的链接。您可以选择更改目标URL。只需要几秒钟,那些您几个月前分享的12个链接就会自动更新。危机得以避免。

现在让我们来看一下用Python创建URL缩短器的代码,我们将需要一个实际执行URL缩短操作的API,因此我们将使用两个不同的API提供商并编写两个不同的Python代码,它们都执行相同的URL缩短任务,只是使用不同的API执行任务。我们将使用的两个API提供商是Bitly URL缩短器和Cuttly URL缩短器。

让我们来看一下Cuttly URL缩短器的代码。

我们可以使用的另一个令人惊叹的URL缩短器是Cuttly URL缩短器。它的使用也相当简单,虽然需要额外的2-3行代码。然而,它不需要安装,因此总体上更容易一些。首先,去Cuttly注册一个新账号。然后,进入“编辑个人资料”并生成新的API密钥。这样我们就会得到一组新的API密钥。记下这些API密钥。因此,我们可以直接开始编程,无需安装任何东西。虽然我们只需要一个简单的安装,但我相信我们大多数人已经安装了它。但是,如果你没有所需的库,安装命令如下:

pip install requests

现在我们需要的库已经准备好了,让我们开始编写代码。

代码

import requests
import sys

#A sample python code to shorten a URL with the use of cutt.ly APIs with different options.
class URLHandler:

    #constructor to initialize the class variables that will be used for the initializing the class variables of the above-written class
    def __init__(self):
        self.api_key = None
        self.shortened_url = None
        self.exception_encountered  = None

# A sample function that will be sued to Set the  API value  which we will use to shorten the input URL that will be provided by the user
    def set_api_url(self):
        print("enter the api key of the service account::")
        input_api_key = input()
        self.api_url = input_api_key

#  this function is a written explicitly  to take an input URL from the user that will be used to short
    def get_input_url(self):
        print("Enter the URL that you want to shorten.")
        url_to_shorten = input()
        return url_to_shorten

#  this function is written to perform the shorter operation on the input URL there is one parameter that is specified for this particular function and this parameter is the URL  parameter that is representing the input URL provided by the user.  try-catch block is implemented in this function so that if some exception is encountered while shortening the input URL which is provided by the user that  exception is handled  and the value of the shortened URL variable is set to none which represents that there is some error exception which is encountered while performing the shortening operation of the specified URL,  and if the operation is successful and no error exception is encountering while shortening the input URL provided by the user the shorten URL variable is set with the actual shorten URL which is returned by the API call that we have given in this function If the exception or errors encountered while shortening the input URL there are a couple of steps that are performed first of all the shortened URL variable is set to none representing there is an exception and along with that the message associated with the exception or error which is encounter is also printed to the user representing the root cause of the exception that is encounter 
    def shorten_url(self,url):
        api_url = f"https://cutt.ly/api/api.php?key={self.api_key}&short={url}"
        request_return_obj = requests.get(self.api_url).json()["url"]

        try:
            if request_return_obj["status"] == 7:
                self.shortened_url = request_return_obj["shortLink"]
            else:
                self.shortened_url = None    
        except Exception as e:
            self.exception_encountered  = e




# This function is written to print the result of the above Return function,  the printing of the shortened URL is done with the logic,  we have an if else block checking whether the shortening of URL operation is performed successfully or not,  for that, we are checking the value of the shortened URL variable if the value is not set to null then that means the operation is performed successfully and that particular URL is printed which is shortened on the other hand if the value is set to none that means there is some exception which is encountered during the shortening operation so in that case the associated exception or error message which is encountered during that operation is presented to the user 
    def print_shortened_url(self):

        if self.shortened_url:
            print("Shortened URL: {}".format(self.shortened_url))
        else :
            print("URL shortening got an exception {}.".format(self.exception_encountered))



# And this is the main function in this function the object of the above-written class is created and that object is used to call all the above-written functions inside that class,  the user is given multiple options like to enter the API key of the service account,  to enter the URL which the user wants to shorten,  to perform the actual shortening operation of the specified input URL,   once the sorting operation is performed successfully the user can print the URL which is shortened,  and in the last option user can accept the code execution by opting the last and final option,  appropriate input is taken from the user and appropriate output is given according to the option which is selected by the user to perform the operation.
def main():

    shortner =  URLHandler()
    url = None
    while(True):
        print("Please choose any one of the operations from the listed below the list of operations::")
        print("1. To enter the API key for the service account.")
        print("2. To enter the URL which you want to shorten.")
        print("3. To perform the operation of shortening the URL.")
        print("4. To print the URL which is shortened.")
        print("5. To exit from the code execution.")

        menu_choice = input()
        menu_choice = int(menu_choice)

        if menu_choice == 1:
            shortner.set_api_url()
        elif menu_choice == 2:
            url = shortner.get_input_url()
        elif menu_choice == 3:
            # shortner.shorten_url(url)
            print("URL shortned successfully.")
        elif menu_choice == 4:
            shortner.print_shortened_url()
        elif menu_choice == 5:
            sys.exit()

        print("To keep on going with code execution, type [y] otherwise [n].")
        continue_or_exit = input()

        if continue_or_exit == 'y' or continue_or_exit == 'Y':
            pass
        elif continue_or_exit == 'n' or continue_or_exit == 'N':
            sys.exit()

if __name__ == '__main__':
    main()

输出:

现在让我们来看一下编写的代码的输出,代码在执行时生成的所有输出都会显示在下面,包括所有标准输出以及任何错误和异常。

please choose any one of the operations from the listed below the list of operations::
1. To enter the API key for the service account.
2. To enter the URL which you want to shorten.
3. To perform the operation of shortening the URL.
4. To print the URL which is shortened.
5. To exit from the code execution.
1
enter the API key of the service account::
UIWN56645G#YW
To keep on going with code execution, type [y] otherwise [n].
y
please choose any one of the operations from the listed below the list of operations::
1. To enter the API key for the service account.
2. To enter the URL which you want to shorten.
3. To perform the operation of shortening the URL.
4. To print the URL which is shortened.
5. To exit from the code execution.
2
Enter the URL that you want to shorten.
https://www.mywebsite.com/dashboard/stats/barchart
To keep on going with code execution, type [y] otherwise [n].
y
please choose any one of the operations from the listed below the list of operations::
1. To enter the API key for the service account.
2. To enter the URL which you want to shorten.
3. To perform the operation of shortening the URL.
4. To print the URL which is shortened.
5. To exit from the code execution.
3
URL shortened successfully.
To keep on going with code execution, type [y] otherwise [n].
y
please choose any one of the operations from the listed below the list of operations::
1. To enter the API key for the service account.
2. To enter the URL which you want to shorten.
3. To perform the operation of shortening the URL.
4. To print the URL which is shortened.
5. To exit from the code execution.
4
Shortened URL:https://cut.ly/i4tdxaE 
To keep on going with code execution, type [y] otherwise [n].
Y
please choose any one of the operations from the listed below the list of operations::
1. To enter the API key for the service account.
2. To enter the URL which you want to shorten.
3. To perform the operation of shortening the URL.
4. To print the URL which is shortened.
5. To exit from the code execution.
2
Enter the URL that you want to shorten.
https://website.
To keep on going with code execution, type [y] otherwise [n].
y
please choose any one of the operations from the listed below the list of operations::
1. To enter the API key for the service account.
2. To enter the URL which you want to shorten.
3. To perform the operation of shortening the URL.
4. To print the URL which is shortened.
5. To exit from the code execution.
3
URL shortened successfully.
To keep on going with code execution, type [y] otherwise [n].
y
please choose any one of the operations from the listed below the list of operations::
1. To enter the API key for the service account.
2. To enter the URL which you want to shorten.
3. To perform the operation of shortening the URL.
4. To print the URL which is shortened.
5. To exit from the code execution.
4
URL shortening got an exception None.


please choose any one of the operations from the listed below the list of operations::
1. To enter the API key for the service account.
2. To enter the URL which you want to shorten.
3. To perform the operation of shortening the URL.
4. To print the URL which is shortened.
5. To exit from the code execution.
5

在上述代码中,创建了上述类的对象,并且该对象用于调用该类中的所有上述函数,用户可以选择输入服务帐户的API密钥,输入要缩短的URL,执行指定输入URL的实际缩短操作,一旦缩短操作成功执行,用户可以打印缩短的URL,在最后一个选项中,用户可以通过选择最后一个选项来接受代码执行,从用户获取适当的输入,并根据用户选择的操作选项提供适当的输出。

让我们来看一下Bitly URL缩短器的代码。

Bitly URL缩短器非常易于使用。您只需要创建一个Bitly帐户。然后转到组设置并从下拉菜单中选择高级设置。该选项中可能会找到API。因为不再支持API,请选择OAuth。之后,创建OAuth令牌。复制该令牌。Bitly是一个URL缩短服务和链接管理平台,由Bitly,Inc于2008年创建。它位于纽约市,是一家私营公司。Bitly每月为社交媒体,短信和电子邮件缩短600百万个URL[4]。Bitly通过收费获取由大量用户使用缩短URL生成的聚合数据访问来赚钱。

代码

import sys
from pyshorteners import Shortener 

class URLShortner:

    #constructor to initialize the class variables that will be used for the initializing the class variables of the above-written class
    def __init__(self):
        self.bitly_api_token = None
        self.shortened_url = None
        self.long_url = None
        self.exception_encountered  = None
#A sample function that will be sued to Set the  API value  which we will use to shorten the input URL that will be provided by the user
    def set_api_url(self):
        print("enter the api token for the bitly service account::")
        input_api_key = input()
        self.api_url = input_api_key

#this function is a written explicitly  to take an input URL from the user that will be used to short
    def get_input_url(self):
        print("Enter the URL that you want to shorten.")
        url_to_shorten = input()
        return url_to_shorten

#this function is written to perform the shorter operation on the input URL there is one parameter that is specified for this particular function and this parameter is the URL  parameter that is representing the input URL provided by the user.  try-catch block is implemented in this function so that if some exception is encountered while shortening the input URL which is provided by the user that  exception is handled  and the value of the shortened URL variable is set to none which represents that there is some error exception which is encountered while performing the shortening operation of the specified URL,  and if the operation is successful and no error exception is encountering while shortening the input URL provided by the user the shorten URL variable is set with the actual shorten URL which is returned by the API call that we have given in this function If the exception or errors encountered while shortening the input URL there are a couple of steps that are performed first of all the shortened URL variable is set to none representing there is an exception and along with that the message associated with the exception or error which is encounter is also printed to the user representing the root cause of the exception that is encounter 
    def shorten_url(self,url):
        url_shortener = Shortener('Bitly', bitly_token = self.bitly_api_token)
        shortened_url = url_shortener.short(url)

        try:
            self.shortened_url = shortened_url
        except Exception as e:
            self.shortened_url = None
            self.exception_encountered = e

    def get_input_url_to_expand(self):
        print("Enter the URL that you want to expand.")
        url_to_shorten = input()
        return url_to_shorten

#this function is written to perform the expansion operation on the input URL there is one parameter that is specified for this particular function and this parameter is the URL  parameter that is representing the input URL provided by the user.  try-catch block is implemented in this function so that if some exception is encountered while expanding the input URL which is provided by the user that  exception is handled  and the value of the expanded URL variable is set to none which represents that there is some error exception which is encountered while performing the expansion operation of the specified URL,  and if the operation is successful and no error exception is encountering while expanding the input URL provided by the user the shorten URL variable is set with the actual expanded URL which is returned by the API call that we have given in this function If the exception or errors encountered while expanding the input URL there are a couple of steps that are performed first of all the expanded URL variable is set to none representing there is an exception and along with that the message associated with the exception or error which is encounter is also printed to the user representing the root cause of the exception that is encounter 
    def expand_url(self):
        url_expander = Shortener('Bitly', bitly_token = self.bitly_api_token)
        long_url = url_expander.short(url)
        self.long_url = long_url

# This function is written to print the result of the above Return function,  the printing of the shortened URL is done with the logic,  we have an if-else block checking whether the shortening of URL operation is performed successfully or not,  for that, we are checking the value of the shortened URL variable if the value is not set to null then that means the operation is performed successfully and that particular URL is printed which is shortened on the other hand if the value is set to none that means there is some exception which is encountered during the shortening operation so in that case the associated exception or error message which is encountered during that operation is presented to the user 
    def print_shortened_url(self):

        if self.shortened_url:
            print("Shortened URL: {}".format(self.shortened_url))
        else :
            print("URL shortening got an exception {}.".format(self.exception_encountered))

# This function is written to print the result of the above-written function,  the printing of the expanded URL is done with the logic,  we have an if-else block checking whether the expansion of URL operation is performed successfully or not,  for that, we are checking the value of the expanded URL variable if the value is not set to null then that means the operation is performed successfully and that particular URL is printed which is expanded on the other hand if the value is set to none that means there is some exception which is encountered during the expansion operation so in that case the associated exception or error message which is encountered during that operation is presented to the user 

    def print_long_url(self):
        if self.long_url:
            print("Expanded URL: {}".format(self.long_url))
        else :
            print("URL expansion got an exception {}.".format(self.exception_encountered))



#And this is the main function in this function the object of the above-written class is created and that object is used to call all the above-written functions inside that class,  the user is given multiple options like to enter the API key of the service account,  to enter the URL which the user wants to shorten,  to perform the actual shortening operation of the specified input URL,   once the sorting operation is performed successfully the user can print the URL which is shortened,  and in the last option user can accept the code execution by opting the last and final option,  appropriate input is taken from the user and appropriate output is given according to the option which is selected by the user to perform the operation.

def main():

    shortner =  URLShortner()
    url = None
    while(True):
        print("Please choose any one of the operations from the listed below the list of operations::")
        print("1. To enter the API token for the service account.")
        print("2. To enter the URL which you want to shorten.")
        print("3. To perform the operation of shortening the URL.")
        print("4. To print the URL which is shortened.")
        print("5. To enter the URL which you want to expand.")
        print("6. To perform the expansion operation of the URL.")
        print("7. To print the URL which is expanded.")
        print("8. To exit from the code execution.")

        menu_choice = input()
        menu_choice = int(menu_choice)

        if menu_choice == 1:
            shortner.set_api_url()
        elif menu_choice == 2:
            url = shortner.get_input_url()
        elif menu_choice == 3:
            # shortner.shorten_url(url)
            print("URL shortned successfully.")
        elif menu_choice == 4:
            shortner.print_shortened_url()
        elif menu_choice == 5:
            url = shortner.get_input_url_to_expand()
        elif menu_choice == 6:
            # shortner.expand_url(url)
            print("URL expanded successfully.")
        elif menu_choice == 7:
            shortner.print_long_url()
        elif menu_choice == 8:
            sys.exit()

        print("To keep on going with code execution, type [y] otherwise [n].")
        continue_or_exit = input()

        if continue_or_exit == 'y' or continue_or_exit == 'Y':
            pass
        elif continue_or_exit == 'n' or continue_or_exit == 'N':
            sys.exit()


if __name__ == '__main__':
    main()

输出:

在上面的代码中,创建了上述类的对象,该对象用于调用类内所有上述函数。用户可以选择多个选项,如输入服务帐户的API密钥,输入用户想要缩短的URL,执行指定输入URL的实际缩短操作,一旦成功执行排序操作,用户可以打印缩短的URL,在最后一个选项中,用户可以选择最后一个选项并接受代码执行,从用户获取适当的输入,并根据用户选择的操作选项给出适当的输出。

优点:

  • 洞察力: 测量您发布的每个链接的点击量是URL缩短器最关键的功能之一。根据您用于压缩Web链接的服务,您可以获得访问者的各种详细信息,如按国家或性别分类。您还可以看到您的哪些社交媒体渠道或帖子引起了最大的兴趣。
  • 增加分享: 观众会发现在自己的帖子中点击、复制和分享缩短的链接更简单,这将有助于您的内容获得有机的社交媒体曝光。
  • 专业性:您的受众可能习惯于以缩短链接形式共享内容。如果您共享一个未经压缩的URL,他们可能会注意到,因为这种方法非常常见。习惯了更整洁、缩写链接的观众可能认为长形式URL不整洁或混乱。
  • 方便性: 分享一个小链接比分享一个复杂的大链接要简单得多。如果您的受众无法直接点击您的链接,或者如果您正在一对一地宣传您的网站,这一点尤为重要。URL缩短器可以帮助您生成一个简洁、易记的链接,无论您是在作PowerPoint演示还是与潜在客户分享链接,都可以立即放入智能手机或Web浏览器中。
  • 更强的参与度: 您的受众更容易记住缩短的URL,尤其是与您的品牌相关的URL。根据Rebrandly的数据,缩短URL可以提高39%的互动率。
  • 更高的点击率: 在社交媒体上,人们习惯于看到缩写的URL。因此,缩短您的链接将提高您的点击率。这是提高帖子策略效果的最简单的修改之一。您还不相信吗?自己查看分析数据!能够追踪缩短URL的进展已经非常有用。

所以,在本文中,我们了解了如何在Python中实现URL缩短器。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程