70行代码展现我的“毕生”编程能力
#!/usr/bin/env python3
coding: utf-8
‘’’
filename = ‘get_url.py’
Author = ‘梦幻精灵_cq’
‘’’
def curl_url(
url: str, # 页面地址
n: int=-1 # 切片索引止
):
‘’’ 页面源码文本获取 ‘’’
import subprocess # 加载子进程运行curl
cmd = (
‘curl’, # 页面get指令
‘-s’, # 静默参数
url
)
return subprocess.check_output(
cmd,
text=True
)[:n] # 获取指令集合返回值(文本)
def request_url(
url: str, # 页面地址
n: int=-1 # 切片索引止
):
‘’’ 页面源码文本获取 ‘’’
import urllib.request as request
return request.urlopen(url).read().decode(‘utf-8’)[:n] # urllib.requst.urlopen(url).read()读取页面是二进制,需要用utf-8字符集解码
def strfcolor(
color: int | str=36
):
return f"\033[{color}m"
def runing_tip(
tip: str=’ 程序正在运行…… ',
n: int=6 # 双宽字符数
):
from os import get_terminal_size
width = get_terminal_size().columns
return (
f"{tip:-^{width - n}}" if tip
else ’ '*width
)
if name == ‘main’:
url = ‘https://blog.csdn.net/m0_57158496/article/details/152706511’ # 我的一篇csdn博文id
print(runing_tip(’ 正在读取页面…… ‘, 6), end=’\r’)
text = curl_url(url, 88)
text2 = request_url(url, 188)
print(runing_tip(’’), end=’\r’)
print(
f"{strfcolor()}\n\nLinux指令get url页面:{strfcolor(0)}"
f"\n{text}"
f"{strfcolor()}\n\nPython urllib.request get url页面:{strfcolor(0)}"
f"\n{text2}"
)