Python 自動化腳本編寫五個實戰案例
Python 自動化腳本編寫是提高工作效率的重要手段。無論是數據處理、文件操作還是網絡請求,Python 都能輕松應對。本文將通過五個實戰案例,帶你逐步掌握 Python 自動化腳本的編寫方法。
案例一:批量重命名文件
(1) 問題描述
假設你有一個文件夾,里面有很多圖片文件,但文件名雜亂無章。你需要將這些文件按順序重命名,例如 image1.jpg, image2.jpg 等。
(2) 解決方案
我們可以使用 Python 的 os 模塊來實現文件重命名。
import os
# 定義文件夾路徑
folder_path = 'path/to/your/folder'
# 獲取文件夾中的所有文件
files = os.listdir(folder_path)
# 過濾出圖片文件(假設只有 .jpg 格式)
image_files = [f for f in files if f.endswith('.jpg')]
# 按文件名排序
image_files.sort()
# 重命名文件
for i, file_name in enumerate(image_files):
# 構建新的文件名
new_name = f'image{i + 1}.jpg'
# 構建完整路徑
old_path = os.path.join(folder_path, file_name)
new_path = os.path.join(folder_path, new_name)
# 重命名文件
os.rename(old_path, new_path)
print(f'Renamed {file_name} to {new_name}')
(3) 代碼解釋
- os.listdir(folder_path):獲取指定文件夾中的所有文件名。
- f.endswith('.jpg'):過濾出以 .jpg 結尾的文件。
- os.rename(old_path, new_path):將文件從舊路徑重命名為新路徑。
案例二:定時發送郵件
(1) 問題描述
假設你需要每天定時發送一封包含最新報告的郵件給客戶。
(2) 解決方案
我們可以使用 smtplib 和 email 模塊來發送郵件,并使用 schedule 模塊來定時執行任務。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import schedule
import time
# 郵件配置
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_user = 'your_email@example.com'
smtp_password = 'your_password'
to_email = 'client_email@example.com'
def send_email():
# 創建郵件對象
msg = MIMEMultipart()
msg['From'] = smtp_user
msg['To'] = to_email
msg['Subject'] = 'Daily Report'
# 添加郵件正文
body = 'Here is the latest report.'
msg.attach(MIMEText(body, 'plain'))
# 發送郵件
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(smtp_user, smtp_password)
server.sendmail(smtp_user, to_email, msg.as_string())
print('Email sent successfully')
# 定時任務
schedule.every().day.at("10:00").do(send_email)
while True:
schedule.run_pending()
time.sleep(1)
(3) 代碼解釋
- MIMEMultipart():創建一個多部分的郵件對象。
- msg.attach(MIMEText(body, 'plain')):添加郵件正文。
- server.starttls():啟用 TLS 加密。
- schedule.every().day.at("10:00").do(send_email):每天 10:00 執行 send_email 函數。
案例三:數據抓取和處理
(1) 問題描述
假設你需要從一個網站上抓取數據,并將其保存到本地文件中。
(2) 解決方案
我們可以使用 requests 和 BeautifulSoup 模塊來抓取網頁數據,并使用 pandas 模塊來處理數據。
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 目標 URL
url = 'https://example.com/data'
# 發送請求
response = requests.get(url)
response.raise_for_status() # 檢查請求是否成功
# 解析 HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 提取數據
data = []
table = soup.find('table')
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [col.text.strip() for col in cols]
data.append(cols)
# 轉換為 DataFrame
df = pd.DataFrame(data[1:], columns=data[0])
# 保存到 CSV 文件
df.to_csv('data.csv', index=False)
print('Data saved to data.csv')
(3) 代碼解釋
- requests.get(url):發送 HTTP GET 請求。
- BeautifulSoup(response.text, 'html.parser'):解析 HTML 內容。
- table.find_all('tr'):找到所有的表格行。
- df.to_csv('data.csv', index=False):將數據保存到 CSV 文件。
案例四:自動化測試
(1) 問題描述
假設你需要對一個 Web 應用進行自動化測試,驗證其功能是否正常。
(2) 解決方案
我們可以使用 Selenium 模塊來模擬用戶操作。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
# 配置 WebDriver
driver = webdriver.Chrome()
# 打開目標網站
driver.get('https://example.com/login')
# 輸入用戶名和密碼
username_input = driver.find_element(By.NAME, 'username')
password_input = driver.find_element(By.NAME, 'password')
username_input.send_keys('test_user')
password_input.send_keys('test_password')
# 提交表單
password_input.send_keys(Keys.RETURN)
# 等待頁面加載
time.sleep(2)
# 檢查登錄是否成功
if 'Dashboard' in driver.page_source:
print('Login successful')
else:
print('Login failed')
# 關閉瀏覽器
driver.quit()
(3) 代碼解釋
- webdriver.Chrome():啟動 Chrome 瀏覽器。
- driver.find_element(By.NAME, 'username'):找到用戶名輸入框。
- username_input.send_keys('test_user'):輸入用戶名。
- password_input.send_keys(Keys.RETURN):提交表單。
- driver.page_source:獲取當前頁面的源代碼。
案例五:自動化備份數據庫
(1) 問題描述
假設你需要定期備份 MySQL 數據庫,并將備份文件上傳到云存儲服務。
(2) 解決方案
我們可以使用 subprocess 模塊來執行命令行操作,并使用 boto3 模塊來上傳文件到 Amazon S3。
import subprocess
import boto3
import os
import datetime
# 數據庫配置
db_host = 'localhost'
db_user = 'root'
db_password = 'password'
db_name = 'mydatabase'
# S3 配置
s3_bucket = 'your-bucket-name'
s3_key = 'backups/'
# 生成備份文件名
backup_file = f'{db_name}_{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}.sql'
# 執行備份命令
backup_command = f'mysqldump -h {db_host} -u {db_user} -p{db_password} {db_name} > {backup_file}'
subprocess.run(backup_command, shell=True, check=True)
print(f'Database backup created: {backup_file}')
# 上傳到 S3
s3 = boto3.client('s3')
s3.upload_file(backup_file, s3_bucket, s3_key + backup_file)
print(f'Backup uploaded to S3: {s3_key + backup_file}')
# 刪除本地備份文件
os.remove(backup_file)
print('Local backup file deleted')
(3) 代碼解釋
- subprocess.run(backup_command, shell=True, check=True):執行備份命令。
- boto3.client('s3'):創建 S3 客戶端。
- s3.upload_file(backup_file, s3_bucket, s3_key + backup_file):上傳文件到 S3。
- os.remove(backup_file):刪除本地備份文件。
實戰案例:自動化生成報表并發送郵件
(1) 問題描述
假設你需要每天生成一份銷售報表,并將其發送給管理層。
(2) 解決方案
我們可以結合前面的案例,使用 pandas 處理數據,使用 matplotlib 生成圖表,使用 smtplib 發送郵件。
import pandas as pd
import matplotlib.pyplot as plt
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import schedule
import time
# 讀取銷售數據
sales_data = pd.read_csv('sales_data.csv')
# 生成圖表
plt.figure(figsize=(10, 6))
plt.plot(sales_data['date'], sales_data['amount'])
plt.title('Sales Report')
plt.xlabel('Date')
plt.ylabel('Amount')
plt.savefig('sales_report.png')
# 創建郵件對象
msg = MIMEMultipart()
msg['From'] = 'your_email@example.com'
msg['To'] = 'manager_email@example.com'
msg['Subject'] = 'Daily Sales Report'
# 添加郵件正文
body = 'Please find the attached sales report.'
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open('sales_report.png', 'rb') as f:
img = MIMEApplication(f.read(), _subtype='png')
img.add_header('Content-Disposition', 'attachment', filename='sales_report.png')
msg.attach(img)
# 發送郵件
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login('your_email@example.com', 'your_password')
server.sendmail('your_email@example.com', 'manager_email@example.com', msg.as_string())
print('Email sent successfully')
# 定時任務
schedule.every().day.at("12:00").do(send_email)
while True:
schedule.run_pending()
time.sleep(1)
(3) 代碼解釋
- pd.read_csv('sales_data.csv'):讀取銷售數據。
- plt.plot(sales_data['date'], sales_data['amount']):生成銷售圖表。
- MIMEApplication(f.read(), _subtype='png'):創建附件。
- schedule.every().day.at("12:00").do(send_email):每天 12:00 執行 send_email 函數。
總結
本文通過五個實戰案例,詳細介紹了如何使用 Python 編寫自動化腳本。從批量重命名文件、定時發送郵件、數據抓取和處理、自動化測試到自動化備份數據庫,每個案例都提供了詳細的代碼示例和解釋。最后,我們還提供了一個綜合實戰案例,展示了如何生成報表并發送郵件。