Python自动化脚本应用与示例

B站影视 港台电影 2025-03-31 13:18 1

摘要:Python 是编写自动化脚本的绝佳选择,因其语法简洁、库丰富且跨平台兼容性强。以下是 Python 自动化脚本的常见应用场景及示例,帮助你快速上手:

Python 是编写自动化脚本的绝佳选择,因其语法简洁、库丰富且跨平台兼容性强。以下是 Python 自动化脚本的常见应用场景及示例,帮助你快速上手:

一、常见自动化场景

文件与目录操作

Ø 批量重命名文件

Ø 清理临时文件/重复文件

Ø 自动备份重要数据

Ø 文件格式批量转换(如 .txt 转 .csv)

网页操作与爬虫

Ø 自动填写表单/提交数据

Ø 网页内容抓取(新闻、价格监控)

Ø 定时检查网站更新

数据处理

Ø 自动化 Excel/CSV 数据处理

Ø 生成统计报告并发送邮件

Ø 数据库定期备份与清洗

系统管理

Ø 监控系统资源(CPU、内存)

Ø 自动化部署服务器

Ø 批量管理远程设备(SSH)

日常办公

Ø 自动发送邮件/短信

Ø 定时提醒任务

Ø 自动化操作 GUI 软件(如 Excel、浏览器)

二、Python 自动化常用库

库名用途os/shutil文件和目录操作subprocess执行系统命令requestsHTTP 请求与网页交互selenium浏览器自动化(动态网页)beautifulsoup4网页内容解析(静态网页)pandas数据处理与分析openpyxl/xlrdExcel 文件操作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)

通过结合具体需求选择合适的库和工具,你可以快速实现高效的自动化流程!

来源:老客数据一点号

相关推荐