云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

Python自动化脚本应用与示例(pythonui自动化脚本)

jxf315 2025-04-11 00:03:53 教程文章 28 ℃

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


一、常见自动化场景

  1. 文件与目录操作

O 批量重命名文件

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

O 自动备份重要数据

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

  1. 网页操作与爬虫

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

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

O 定时检查网站更新

  1. 数据处理

O 自动化 Excel/CSV 数据处理

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

O 数据库定期备份与清洗

  1. 系统管理

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

O 自动化部署服务器

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

  1. 日常办公

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) # 每分钟检查一次


四、进阶技巧

  1. 异常处理
    使用 try...except 增强脚本健壮性:

python

try:

os.remove("temp_file.txt")

except FileNotFoundError:

print("文件不存在,无需删除")

  1. 日志记录
    使用 logging 模块记录运行状态:

python

import logging

logging.basicConfig(filename='automation.log', level=logging.INFO)

logging.info("脚本开始运行")

  1. 跨平台兼容性
    使用 pathlib 处理路径:

python

from pathlib import Path

file_path = Path("documents") / "data.csv"

  1. 无界面运行(Headless)
    Selenium 无头模式示例:

python

from selenium.webdriver import ChromeOptions

options = ChromeOptions()

options.add_argument("--headless=new")

driver = webdriver.Chrome(options=options)


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

Tags:

最近发表
标签列表