1. 为什么需要Python自动化脚本?
每天重复点击鼠标、复制粘贴数据、整理文件...这些机械性工作正在吞噬我们宝贵的时间。作为从业十年的Python开发者,我深刻体会到:能用代码解决的问题,绝不动手操作。Python凭借简洁语法和丰富生态,成为自动化任务的首选工具。
最近整理了10个经过实战检验的脚本,覆盖文件处理、网页操作、办公自动化等高频场景。这些代码都经过生产环境验证,你可以在以下环境直接运行:
- Python 3.6+
- 常见操作系统(Windows/macOS/Linux)
- 无需特殊硬件配置
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 文件管理自动化方案
2.1 智能文件分类器
这个脚本能根据扩展名自动归类下载文件夹中的文件。我经常看到同事手动整理上百个文件,其实用30行代码就能解决:
python复制import os
import shutil
def auto_classify(download_path="~/Downloads"):
file_types = {
'images': ['.jpg', '.png', '.gif'],
'documents': ['.pdf', '.docx', '.txt'],
'archives': ['.zip', '.rar']
}
for filename in os.listdir(download_path):
if os.path.isfile(os.path.join(download_path, filename)):
file_ext = os.path.splitext(filename)[1].lower()
for folder, extensions in file_types.items():
if file_ext in extensions:
target_dir = os.path.join(download_path, folder)
os.makedirs(target_dir, exist_ok=True)
shutil.move(
os.path.join(download_path, filename),
os.path.join(target_dir, filename)
)
break
关键技巧:使用
exist_ok=True避免重复创建文件夹,比先检查再创建更高效
2.2 重复文件清理工具
这个脚本通过MD5校验识别重复文件,我的照片库用它清理出20GB空间:
python复制import hashlib
import os
def find_duplicates(root_dir):
hashes = {}
for dirpath, _, filenames in os.walk(root_dir):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
with open(filepath, 'rb') as f:
file_hash = hashlib.md5(f.read()).hexdigest()
if file_hash in hashes:
print(f"发现重复文件: {filepath} 与 {hashes[file_hash]}")
else:
hashes[file_hash] = filepath
避坑指南:大文件读取可能内存溢出,可改为分块读取:
python复制def md5_chunked(filepath, chunk_size=8192): hash_md5 = hashlib.md5() with open(filepath, "rb") as f: for chunk in iter(lambda: f.read(chunk_size), b""): hash_md5.update(chunk) return hash_md5.hexdigest()
3. 网页自动化实战技巧
3.1 自动填写网页表单
用Selenium实现问卷自动填写,效率提升10倍:
python复制from selenium import webdriver
from selenium.webdriver.common.by import By
import time
def auto_survey(url):
driver = webdriver.Chrome()
driver.get(url)
# 等待页面加载
time.sleep(2)
# 定位并填写表单
name_field = driver.find_element(By.ID, "name")
name_field.send_keys("张三")
# 单选按钮选择
driver.find_element(By.XPATH, "//input[@value='option1']").click()
# 提交表单
submit_btn = driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
submit_btn.click()
driver.quit()
实战经验:使用
WebDriverWait比固定sleep更可靠:python复制from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "dynamic-element")) )
3.2 定时网页截图监控
这个脚本每天定时对关键页面截图存档:
python复制from selenium import webdriver
import schedule
import time
def take_screenshot(url, save_path):
driver = webdriver.Chrome()
driver.get(url)
driver.save_screenshot(save_path)
driver.quit()
# 设置每天9点执行
schedule.every().day.at("09:00").do(
take_screenshot,
url="https://example.com",
save_path="/path/to/screenshot.png"
)
while True:
schedule.run_pending()
time.sleep(60)
4. 办公自动化高效方案
4.1 Excel报表自动生成
用openpyxl自动生成周报,省去每周2小时手工操作:
python复制from openpyxl import Workbook
from openpyxl.styles import Font, Alignment
import datetime
def generate_report(data):
wb = Workbook()
ws = wb.active
# 设置标题样式
title_font = Font(bold=True, size=14)
ws['A1'] = "销售周报"
ws['A1'].font = title_font
# 写入数据
for row in data:
ws.append(row)
# 自动调整列宽
for col in ws.columns:
max
