1. 为什么Python是自动化脚本的首选语言?
Python在自动化领域占据绝对优势并非偶然。作为从业10年的开发者,我亲历了从Perl到Python的自动化工具迁移浪潮。Python的杀手锏在于其"胶水语言"特性——标准库内置了文件操作(os)、系统调用(subprocess)、日期处理(datetime)等自动化刚需模块,配合requests、selenium等第三方库,几乎能覆盖所有自动化场景。
更关键的是Python的跨平台兼容性。同一段脚本在Windows、Mac和Linux上只需微调路径分隔符就能运行,这在需要多环境部署时优势尽显。去年我用Python为团队开发的自动化测试框架,仅用3天就完成了从Windows开发机到Linux云服务器的迁移,这种效率其他语言难以企及。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 文件管理自动化:解放重复劳动
2.1 智能文件整理脚本
这个脚本我每周都在用,它能根据扩展名自动归类下载文件夹中的文件。核心是os模块的walk()和rename()方法:
python复制import os
import shutil
download_folder = '/Users/me/Downloads'
file_types = {
'images': ['.jpg', '.png'],
'documents': ['.pdf', '.docx']
}
for filename in os.listdir(download_folder):
file_ext = os.path.splitext(filename)[1].lower()
for folder_name, extensions in file_types.items():
if file_ext in extensions:
target_folder = os.path.join(download_folder, folder_name)
if not os.path.exists(target_folder):
os.makedirs(target_folder)
shutil.move(
os.path.join(download_folder, filename),
os.path.join(target_folder, filename)
)
提示:添加try-except块处理文件权限错误,这是实际使用中最常见的异常
2.2 批量重命名工具
摄影师和设计师必备,我用这个脚本处理过上万张产品图。关键技巧是用正则表达式提取元数据:
python复制import re
from pathlib import Path
pattern = re.compile(r'IMG_(\d{4})(\d{2})(\d{2})')
for img_file in Path('photos').glob('*.jpg'):
match = pattern.search(img_file.name)
if match:
new_name = f"{match.group(1)}-{match.group(2)}-{match.group(3)}_product.jpg"
img_file.rename(img_file.with_name(new_name))
3. 网络操作自动化:告别重复点击
3.1 自动表单填写
我用selenium+chromedriver帮市场部自动填写了300+份供应商问卷。核心是定位元素的三种策略:
python复制from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get("https://example.com/form")
# 最佳实践:优先用CSS选择器
driver.find_element(By.CSS_SELECTOR, "#username").send_keys("admin")
Select(driver.find_element(By.NAME, "department")).select_by_value("IT")
driver.find_element(By.XPATH, "//button[text()='Submit']").click()
注意:添加implicitly_wait(10)防止元素加载延迟导致的报错
3.2 网页内容监控
这个脚本帮我抢到了多场演唱会门票。关键技术点是BeautifulSoup的CSS选择器和requests的session保持:
python复制import requests
from bs4 import BeautifulSoup
import time
def check_ticket(url, keyword):
with requests.Session() as s:
while True:
resp = s.get(url)
soup = BeautifulSoup(resp.text, 'html.parser')
if keyword in soup.select_one('.ticket-status').text:
print("Ticket available!")
break
time.sleep(300) # 5分钟检查一次
4. 数据处理自动化:Excel解放方案
4.1 CSV与Excel转换器
财务部同事最爱的脚本,用openpyxl处理xlsx比pandas更可靠:
python复制from openpyxl import Workbook
import csv
def csv_to_excel(csv_file, excel_file):
wb = Workbook()
ws = wb.active
with open(csv_file, 'r', encoding='utf-8') as f:
for row in csv.reader(f):
ws.append(row)
wb.save(excel_file)
4.2 数据清洗流水线
处理用户调研数据时,这个脚本帮我节省了80%时间:
python复制import pandas as pd
def clean_data(raw_file):
df = pd.read_excel(raw_file)
df = df.dropna(subset=['email']) # 删除无邮箱记录
df['phone'] = df['phone'].str.replace(r'\D', '', regex=True) # 标准化电话号码
df.to_excel('cleaned_data.xlsx', index=False)
5. 系统管理自动化:运维利器
5.1 日志分析报警
用这个脚本我们发现了多次服务器异常:
python复制import re
from datetime import datetime
error_pattern = re.compile(r'ERROR.*?(20\d{2}-\d{2}-\d{2})')
last_hour = datetime.now().hour - 1
with open('/var/log/app.log') as f:
errors = [line for line in f if error_pattern.search(line)
and datetime.strptime(error_pattern.search(line).group(1), '%Y-%m-%d').hour == last_hour]
if len(errors) > 10:
send_alert_email(f"发现{len(errors)}条错误日志")
5.2 自动备份工具
结合crontab实现每日数据库备份:
python复制import subprocess
from datetime import date
today = date.today().isoformat()
dump_cmd = f"mysqldump -u root -p'mypwd' mydb > /backups/mydb_{today}.sql"
subprocess.run(dump_cmd, shell=True, check=True)
6. 图像处理自动化:设计师助手
6.1 批量图片压缩
用Pillow处理产品图,保持画质的同时减小75%体积:
python复制from PIL import Image
import os
def compress_image(input_path, quality=30):
output_path = os.path.splitext(input_path)[0] + "_compressed.jpg"
with Image.open(input_path) as img:
img.save(output_path, "JPEG", quality=quality, optimize=True)
6.2 水印添加工具
保护公司图片版权的必备脚本:
python复制from PIL import Image, ImageDraw, ImageFont
def add_watermark(image_path, text):
original = Image.open(image_path)
watermark = Image.new('RGBA', original.size)
draw = ImageDraw.Draw(watermark)
font = ImageFont.truetype('arial.ttf', 40)
# 斜向填充水印
for i in range(0, watermark.size[0], 200):
for j in range(0, watermark.size[1], 200):
draw.text((i,j), text, font=font, fill=(255,255,255,128))
return Image.alpha_composite(original.convert('RGBA'), watermark)
7. 邮件处理自动化:高效沟通
7.1 自动邮件分类器
用imaplib实现收件箱自动归类:
python复制import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('me@gmail.com', 'password')
mail.select('inbox')
typ, data = mail.search(None, 'UNSEEN')
for num in data[0].split():
typ, msg_data = mail.fetch(num, '(RFC822)')
msg = email.message_from_bytes(msg_data[0][1])
if 'invoice' in msg['Subject'].lower():
mail.copy(num, 'INBOX/Invoices')
mail.store(num, '+FLAGS', '\\Deleted')
mail.expunge()
7.2 定时邮件发送
市场活动邮件的定时发送解决方案:
python复制import smtplib
from email.mime.text import MIMEText
from datetime import datetime
def send_scheduled_email(to, subject, body, send_time):
while datetime.now() < send_time:
time.sleep(60)
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = 'noreply@company.com'
msg['To'] = to
with smtplib.SMTP('smtp.company.com') as server:
server.send_message(msg)
8. 社交媒自动化:运营神器
8.1 Twitter自动回复机器人
用tweepy库实现关键词自动回复:
python复制import tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
if '#help' in status.text.lower():
api.update_status(
f"@{status.user.screen_name} 已收到您的求助,客服将尽快联系您!",
in_reply_to_status_id=status.id
)
my_stream = tweepy.Stream(auth=api.auth, listener=MyStreamListener())
my_stream.filter(track=['#help'])
8.2 Instagram图片自动发布
通过instabot实现定时发图:
python复制from instabot import Bot
import time
bot = Bot()
bot.login(username="my_account", password="password")
def post_to_instagram(image_path, caption):
bot.upload_photo(image_path, caption=caption)
# 避免频繁操作被封号
time.sleep(3600)
9. 开发效率自动化:程序员必备
9.1 代码质量检查器
用flake8实现提交前自动检查:
python复制import subprocess
import sys
def pre_commit_check():
result = subprocess.run(['flake8', '--exclude=.venv', '.'], capture_output=True)
if result.returncode != 0:
print("代码规范检查失败:")
print(result.stdout.decode())
sys.exit(1)
9.2 API测试自动化
用requests实现接口自动化测试:
python复制import requests
import json
test_cases = [
{
"url": "/api/login",
"method": "POST",
"data": {"username": "test", "password": "123456"},
"expect": 200
}
]
for case in test_cases:
resp = requests.request(
case["method"],
f"http://localhost:8000{case['url']}",
json=case["data"]
)
assert resp.status_code == case["expect"], f"{case['url']} 测试失败"
10. 生活效率自动化:个人助手
10.1 健康数据追踪
同步智能手表数据到Notion数据库:
python复制import requests
from datetime import datetime
NOTION_TOKEN = "secret_xxx"
DATABASE_ID = "database_id"
def sync_health_data(steps, heart_rate):
headers = {
"Authorization": f"Bearer {NOTION_TOKEN}",
"Content-Type": "application/json",
"Notion-Version": "2022-06-28"
}
payload = {
"parent": {"database_id": DATABASE_ID},
"properties": {
"Date": {"date": {"start": datetime.now().isoformat()}},
"Steps": {"number": steps},
"Heart Rate": {"number": heart_rate}
}
}
requests.post("https://api.notion.com/v1/pages", headers=headers, json=payload)
10.2 智能家居控制
用python-miio控制小米设备:
python复制from miio import AirPurifier
purifier = AirPurifier("192.168.1.100", "token")
def auto_control_purifier(pm25):
if pm25 > 75:
purifier.on()
purifier.set_favorite_level(3)
elif pm25 < 35:
purifier.off()
这些脚本都是我在实际工作中反复打磨过的,每个都配有异常处理和日志记录。建议使用时根据自身环境修改参数,特别是涉及认证信息的部分要做好保密处理。Python自动化的魅力在于,当你把重复劳动交给脚本后,可以腾出时间处理真正需要创造力的工作。
