在数字化办公时代,重复性任务占据了大量工作时间。利用 Python 编写自动化脚本,可以显著减少人工操作,提升工作效率。本文将介绍 10 个实用的 Python 自动化脚本示例,涵盖网页数据提取、多媒体处理、系统监控及移动端自动化等场景,并提供代码实现与注意事项。
1. 解析和提取 HTML
此脚本用于从网页 URL 中提取 HTML 内容并解析特定标签。适用于网络爬虫或需要抓取网页数据的场景。
依赖安装:
pip install gazpacho
代码实现:
import gazpacho
# 提取 HTML 内容
url = 'https://www.example.com/'
html = gazpacho.get(url)
print(html)
# 带请求头提取(模拟浏览器)
headers = {'User-Agent': 'Mozilla/5.0'}
html = gazpacho.get(url, headers=headers)
print(html)
# 解析 HTML
text = gazpacho.Soup(html)
# 查找单个标签
h1_tag = text.find('h1')
span_tag = text.find('span')
# 查找多个标签
paragraphs = text.find_all('p')
links = text.find_all('a')
# 按类名查找
class_tag = text.find('.class-name')
# 按属性查找
div_tag = text.find("div", attrs={"class": "test"})
# 提取文本内容
if h1_tag:
print(h1_tag.text)
注意事项: 部分网站可能反爬,建议遵守 robots.txt 协议,避免高频请求。
2. 二维码扫描仪
该脚本可批量扫描本地二维码图片,适合处理大量图像数据的场景。
依赖安装:
pip install qrtools
代码实现:
from qrtools import Qr
def scan_qr(qr_img_path):
qr = Qr()
try:
qr.decode(qr_img_path)
qr.data
Exception e:
()
result = scan_qr()
result:
()


