网站首页 > 教程文章 正文
Python 是编写自动化脚本的绝佳选择,因其语法简洁、库丰富且跨平台兼容性强。以下是 Python 自动化脚本的常见应用场景及示例,帮助你快速上手:
一、常见自动化场景
- 文件与目录操作
O 批量重命名文件
O 清理临时文件/重复文件
O 自动备份重要数据
O 文件格式批量转换(如 .txt 转 .csv)
- 网页操作与爬虫
O 自动填写表单/提交数据
O 网页内容抓取(新闻、价格监控)
O 定时检查网站更新
- 数据处理
O 自动化 Excel/CSV 数据处理
O 生成统计报告并发送邮件
O 数据库定期备份与清洗
- 系统管理
O 监控系统资源(CPU、内存)
O 自动化部署服务器
O 批量管理远程设备(SSH)
- 日常办公
O 自动发送邮件/短信
O 定时提醒任务
O 自动化操作 GUI 软件(如 Excel、浏览器)
二、Python 自动化常用库
库名 | 用途 |
os/shutil | 文件和目录操作 |
subprocess | 执行系统命令 |
requests | HTTP 请求与网页交互 |
selenium | 浏览器自动化(动态网页) |
beautifulsoup4 | 网页内容解析(静态网页) |
pandas | 数据处理与分析 |
openpyxl/xlrd | Excel 文件操作 |
schedule | 定时任务调度 |
pyautogui | 控制鼠标和键盘(GUI 自动化) |
三、实用脚本示例
1. 批量重命名文件
python
import os
folder_path = "./documents"
for index, filename in enumerate(os.listdir(folder_path)):
new_name = f"report_{index}.txt"
src = os.path.join(folder_path, filename)
dst = os.path.join(folder_path, new_name)
os.rename(src, dst)
2. 网页内容抓取(使用 requests + BeautifulSoup)
python
import requests
from bs4 import BeautifulSoup
url = "https://example.com/news"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for headline in soup.find_all('h2', class_='title'):
print(headline.text.strip())
3. 自动发送邮件(使用 smtplib)
python
import smtplib
from email.mime.text import MIMEText
sender = "your_email@example.com"
receiver = "target@example.com"
password = "your_app_password" # 使用应用专用密码
msg = MIMEText("这是自动发送的测试邮件。")
msg['Subject'] = 'Python自动化邮件'
msg['From'] = sender
msg['To'] = receiver
with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
server.login(sender, password)
server.sendmail(sender, receiver, msg.as_string())
4. 定时任务(使用 schedule 库)
python
import schedule
import time
def daily_backup():
print("开始自动备份数据库...")
# 添加备份代码
schedule.every().day.at("02:00").do(daily_backup)
while True:
schedule.run_pending()
time.sleep(60) # 每分钟检查一次
四、进阶技巧
- 异常处理
使用 try...except 增强脚本健壮性:
python
try:
os.remove("temp_file.txt")
except FileNotFoundError:
print("文件不存在,无需删除")
- 日志记录
使用 logging 模块记录运行状态:
python
import logging
logging.basicConfig(filename='automation.log', level=logging.INFO)
logging.info("脚本开始运行")
- 跨平台兼容性
使用 pathlib 处理路径:
python
from pathlib import Path
file_path = Path("documents") / "data.csv"
- 无界面运行(Headless)
Selenium 无头模式示例:
python
from selenium.webdriver import ChromeOptions
options = ChromeOptions()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)
通过结合具体需求选择合适的库和工具,你可以快速实现高效的自动化流程!
猜你喜欢
- 2025-04-11 手把手教你开发智能备份神器,小白也能30分钟搞定!
- 2025-04-11 画像笔记23- 作业流程调度(2)(作业流程图怎么画)
- 2025-04-11 Python接口自动化之常见用例读取方法介绍
- 2025-04-11 AI办公自动化:批量合并多个Excel表格的数据并汇总
- 2025-04-11 pc端微信用户图片DAT格式解码为图片
- 2025-04-11 21-02-Python-文件操作下(python文件操作方法)
- 2025-04-11 Python定时任务,三步实现自动化(python定时任务,三步实现自动化效果)
- 2025-04-11 自动下载邮箱里未阅读的发票,并用邮件标题里指定的几个字命名
- 2025-04-11 照片整理很繁琐?3个python脚本帮你快速整理照片
- 2025-04-11 Python语言的12个基础知识点小结(python 语言基础)
- 最近发表
- 标签列表
-
- location.href (44)
- document.ready (36)
- git checkout -b (34)
- 跃点数 (35)
- 阿里云镜像地址 (33)
- qt qmessagebox (36)
- md5 sha1 (32)
- mybatis plus page (35)
- semaphore 使用详解 (32)
- update from 语句 (32)
- vue @scroll (38)
- 堆栈区别 (33)
- 在线子域名爆破 (32)
- 什么是容器 (33)
- sha1 md5 (33)
- navicat导出数据 (34)
- 阿里云acp考试 (33)
- 阿里云 nacos (34)
- redhat官网下载镜像 (36)
- srs服务器 (33)
- pico开发者 (33)
- https的端口号 (34)
- vscode更改主题 (35)
- 阿里云资源池 (34)
- os.path.join (33)