用python整个URL缩短器

URL缩短

短网址由于易于记忆和输入,因此在数字营销领域非常受欢迎。

这里给大家介绍一下,如何使用Python创建URL缩短器。
在这里插入图片描述

python答疑 咨询 学习交流群2:660193417###
from __future__ import with_statement
import contextlib
try:
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlencode
try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen
import sys


def make_tiny(url):
    request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url': url}))
    # print(request_url)
    with contextlib.closing(urlopen(request_url)) as response:
        return response.read().decode('utf-8')


def main():
    for tinyurl in map(make_tiny, ['https://baijiahao.baidu.com/s?id=1719379508156841662']):
        print(tinyurl)


if __name__ == '__main__':
    main()

运行代码,输出如下。

# 输出
https://tinyurl.com/y4z6z2gq

猜你喜欢

转载自blog.csdn.net/m0_67575344/article/details/125191223