Python3, 10 lines of code actually shorten the URL, I didn't expect to be able to play like this.

1 Introduction

Xiao Diaosi : Brother Yu, is there any way to make the url shorter?
Xiaoyu : I'll go~ Why did the url mess with you? You make it shorter. ?
Xiao Diaosi : No, I just think that the url is too long, and it is not easy to copy it.
Xiaoyu : That's it?
Little Diaosi : That’s right, that’s it.
Xiaoyu : There is indeed a way.
Little Diaosi : Hehe, I knew you had a way.
Xiaoyu : I knew you just became a member yesterday.
Little Diaosi : ... I'm sorry, you know all this?
Xiaoyu : Guess.
Little Diaosi : Don't make trouble, be serious, teach me how to shorten the url
Xiaoyu : This is not easy to handle.
insert image description here

2. Code combat

2.1 Definition

urllib is a module in the Python standard library that provides a set of functions and methods for working with URLs.
Its features include:

  • Get the content of the URL
  • Visit the specified URL
  • Remove specific parts of the URL
  • Add custom request headers etc.

2.2 Common functions

Next, I also list some commonly used functions of urllib, as well as code examples:

  • urllib.request.urlopen() : Open the specified URL and return an HTTP response object.
    code example
# -*- coding:utf-8 -*-
# @Time   : 2023-07-08
# @Author : Carl_DJ


import urllib.request
'''
打开指定的URL并返回一个HTTP响应对象
'''
url = 'https://blog.csdn.net/wuyoudeyuer'
response = urllib.request.urlopen(url)

print(response.read())
  • urllib.request.urlretrieve() : Download a file from the specified URL and save it to a local file.
    code example
# -*- coding:utf-8 -*-
# @Time   : 2023-07-08
# @Author : Carl_DJ


import urllib.request
'''
从指定的URL下载文件并保存到本地文件
'''
url = 'https://blog.csdn.net/wuyoudeyuer/file.txt'
filename = 'file.txt'
urllib.request.urlretrieve(url, filename)
  • urllib.request.add_header() : Add custom header information to the HTTP request header.
    code example
# -*- coding:utf-8 -*-
# @Time   : 2023-07-08
# @Author : Carl_DJ


import urllib.request
'''
向HTTP请求头中添加自定义的头部信息
'''
url = 'https://blog.csdn.net/wuyoudeyuer'
headers = {
    
    'User-Agent': 'Mozilla/5.0'}
urllib.request.add_header('headers', headers)
  • urllib.request.delete() : Delete the specified URL.
    code example
# -*- coding:utf-8 -*-
# @Time   : 2023-07-08
# @Author : Carl_DJ


import urllib.request
'''
删除指定的URL
'''
url = 'https://blog.csdn.net/wuyoudeyuer'
urllib.request.delete(url)
  • urllib.request.build_request() : Build an HTTP request object.
    code example
# -*- coding:utf-8 -*-
# @Time   : 2023-07-08
# @Author : Carl_DJ


import urllib.request
'''
构建HTTP请求对象
'''

url = 'https://blog.csdn.net/wuyoudeyuer'
req = urllib.request.Request(url)
req.add_header('header', 'value')
response = urllib.request.urlopen(req)
  • urllib.error.URLError : An exception that may occur while processing a URL request.
    code example
# -*- coding:utf-8 -*-
# @Time   : 2023-07-08
# @Author : Carl_DJ

import urllib.error
'''
处理URL请求时可能会发生的异常
'''
try:
    urllib.request.urlopen(url)
except urllib.error.URLError as e:
    print(e)

2.3 Examples

code example

# -*- coding:utf-8 -*-
# @Time   : 2023-07-08
# @Author : Carl_DJ
'''
实现功能:
	让URL变短
'''


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

#定义短url函数
def tiny_url(url):
	#设置请求的url
    request_url = ('http://xxxx.com' +
                   urlencode({
    
    'url': url}))
    with contextlib.closing(urlopen(request_url)) as response:
        return response.read().decode('utf-8')

#定义main函数
def main():
    for tinyurl in map(tiny_url, sys.argv[1:]):
        print(tinyurl)

#运行
if __name__ == '__main__':
    main()

3. Summary

Seeing this, today's content is almost over.
Today I mainly shared a little trick to shorten the url, isn't it fun?

Isn't it interesting to learn a little trick every day?

I am a small fish :

  • CSDN blog expert ;
  • Aliyun expert blogger ;
  • 51CTO blog expert ;
  • 51 certified lecturer, etc .;
  • Certified gold interviewer ;
  • Job interview and training planner ;
  • Certified expert bloggers in several domestic mainstream technical communities ;
  • Winners of the first and second prizes in the evaluation of various mainstream products (Alibaba Cloud, etc.) ;

Follow me and take you to learn more, more professional and prefaced Python technology.

Guess you like

Origin blog.csdn.net/wuyoudeyuer/article/details/131598800