為什麼選擇 Python 做自動化

Python 擁有豐富的函式庫和簡潔的語法,非常適合編寫自動化腳本。

Python 自動化的優勢

  • 簡單易學 - 語法接近自然語言
  • 豐富的函式庫 - 幾乎所有需求都有對應的套件
  • 跨平台 - Windows、macOS、Linux 都支援
  • 活躍的社群 - 問題容易找到解答

實戰案例 1:檔案管理自動化

自動整理下載資料夾

import os
import shutil
from pathlib import Path

def organize_downloads():
    downloads_path = Path.home() / "Downloads"
    
    # 定義檔案類型分類
    file_types = {
        'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
        'documents': ['.pdf', '.doc', '.docx', '.txt', '.xlsx'],
        'videos': ['.mp4', '.avi', '.mkv', '.mov'],
        'archives': ['.zip', '.rar', '.7z', '.tar']
    }
    
    for file_path in downloads_path.iterdir():
        if file_path.is_file():
            file_ext = file_path.suffix.lower()
            
            # 找到對應的資料夾
            for folder, extensions in file_types.items():
                if file_ext in extensions:
                    target_folder = downloads_path / folder
                    target_folder.mkdir(exist_ok=True)
                    
                    # 移動檔案
                    shutil.move(str(file_path), str(target_folder / file_path.name))
                    print(f"移動 {file_path.name}{folder}")
                    break

if __name__ == "__main__":
    organize_downloads()
    print("檔案整理完成!")

實戰案例 2:網頁爬蟲

抓取新聞標題

import requests
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime

def scrape_news(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.content, 'html.parser')
    
    # 根據網站結構調整選擇器
    news_items = soup.find_all('h2', class_='news-title')
    
    news_data = []
    for item in news_items:
        title = item.get_text().strip()
        link = item.find('a')['href'] if item.find('a') else ''
        
        news_data.append({
            'title': title,
            'link': link,
            'scraped_at': datetime.now()
        })
    
    return news_data

def save_to_excel(data, filename):
    df = pd.DataFrame(data)
    df.to_excel(filename, index=False)
    print(f"資料已儲存到 {filename}")

# 使用範例
news_url = "https://example-news-site.com"
news = scrape_news(news_url)
save_to_excel(news, f"news_{datetime.now().strftime('%Y%m%d')}.xlsx")

實戰案例 3:系統監控

伺服器狀態監控

import psutil
import smtplib
from email.mime.text import MIMEText
from datetime import datetime

def check_system_health():
    # 檢查 CPU 使用率
    cpu_percent = psutil.cpu_percent(interval=1)
    
    # 檢查記憶體使用率
    memory = psutil.virtual_memory()
    memory_percent = memory.percent
    
    # 檢查磁碟使用率
    disk = psutil.disk_usage('/')
    disk_percent = (disk.used / disk.total) * 100
    
    return {
        'cpu': cpu_percent,
        'memory': memory_percent,
        'disk': disk_percent,
        'timestamp': datetime.now()
    }

def send_alert(subject, message):
    sender = "[email protected]"
    receiver = "[email protected]"
    password = "your-app-password"
    
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = receiver
    
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(sender, password)
        server.sendmail(sender, receiver, msg.as_string())

def monitor_system():
    health = check_system_health()
    
    alerts = []
    
    if health['cpu'] > 80:
        alerts.append(f"CPU 使用率過高: {health['cpu']:.1f}%")
    
    if health['memory'] > 85:
        alerts.append(f"記憶體使用率過高: {health['memory']:.1f}%")
    
    if health['disk'] > 90:
        alerts.append(f"磁碟使用率過高: {health['disk']:.1f}%")
    
    if alerts:
        message = "\n".join(alerts)
        send_alert("系統警告", message)
        print("已發送警告郵件")
    else:
        print("系統狀態正常")

# 每5分鐘檢查一次
import time
while True:
    monitor_system()
    time.sleep(300)  # 5分鐘

常用自動化函式庫

檔案操作

  • pathlib - 現代化的路徑操作
  • shutil - 高級檔案操作
  • os - 系統操作

網路請求

  • requests - HTTP 請求
  • urllib - URL 處理

資料處理

  • pandas - 資料分析
  • openpyxl - Excel 操作
  • csv - CSV 檔案處理

網頁爬蟲

  • beautifulsoup4 - HTML 解析
  • selenium - 瀏覽器自動化
  • scrapy - 專業爬蟲框架

最佳實踐

  1. 錯誤處理 - 使用 try-except 處理例外
  2. 日誌記錄 - 記錄腳本執行過程
  3. 配置檔案 - 將設定抽離到外部檔案
  4. 測試 - 編寫單元測試
  5. 文檔 - 詳細的註解和說明文件

開始用 Python 自動化你的工作流程吧!