No24: PyAutoGUI 實現桌面自動化
摘要
PyAutoGUI 是一個跨平臺的桌面自動化工具,能夠模擬鼠標點擊、鍵盤輸入、屏幕截圖與圖像識別,適用于重復性桌面任務(如表單填寫、游戲操作、批量文件處理)。本集通過代碼+截圖+輸出日志的實戰形式,帶你掌握從基礎操作到復雜任務的全流程自動化。
核心概念與代碼實戰
1. 基礎操作:鼠標與鍵盤控制
安裝命令:
pip install pyautogui
鼠標控制:
import pyautogui
import time # 移動鼠標到坐標 (500, 300)
pyautogui.moveTo(500, 300, duration=1) # 模擬點擊(左鍵單擊)
pyautogui.click() # 滾輪滾動(向上滾動 200 單位)
pyautogui.scroll(200)
鍵盤輸入:
# 輸入文本
pyautogui.write("Hello, PyAutoGUI!", interval=0.1) # 組合鍵操作(Ctrl+C)
pyautogui.hotkey("ctrl", "c")
效果驗證:
print(f"當前鼠標位置:{pyautogui.position()}") # 輸出實時坐標
2. 截屏與圖像識別
場景:通過屏幕上的圖標定位并點擊按鈕。
# 截取屏幕并保存
screenshot = pyautogui.screenshot()
screenshot.save("screenshot.png") # 查找圖標位置(需提前保存圖標圖片)
button_location = pyautogui.locateOnScreen("submit_button.png")
if button_location: # 計算圖標中心點并點擊 button_center = pyautogui.center(button_location) pyautogui.click(button_center)
else: print("圖標未找到!")
輸出示例:
圖標位置:Box(left=200, top=150, width=50, height=30)
3. 腳本調試與異常處理
問題場景:圖像識別失敗導致腳本崩潰。
解決方案:
try: # 設置超時時間為 5 秒 button_location = pyautogui.locateOnScreen( "save_icon.png", confidence=0.8, # 允許 80% 相似度 grayscale=True # 灰度匹配提升速度 ) if not button_location: raise Exception("圖標匹配失敗!")
except Exception as e: print(f"錯誤:{e}") # 回退到手動輸入坐標 pyautogui.click(100, 200)
調試技巧:
- 使用
pyautogui.PAUSE = 1
控制操作間隔 - 啟用
pyautogui.FAILSAFE = True
(鼠標移至左上角強制停止腳本)
實戰案例
案例 1:自動化填寫表單
場景:批量填寫 Excel 表格中的數據到某個桌面應用。
import pyautogui
import pandas as pd # 讀取 Excel 數據
data = pd.read_excel("data.xlsx") for index, row in data.iterrows(): # 定位輸入框并填寫 pyautogui.click(300, 400) # 姓名輸入框 pyautogui.write(row["姓名"]) pyautogui.press("tab") # 跳轉到年齡輸入框 pyautogui.write(str(row["年齡"])) # 提交表單 pyautogui.press("enter") time.sleep(1) # 等待頁面刷新
輸出示例:
已提交姓名:張三,年齡:25
已提交姓名:李四,年齡:30
案例 2:模擬游戲中的簡單操作
場景:自動玩“鍵盤反應速度”游戲。
# 監聽屏幕特定區域的變化
game_region = (400, 200, 200, 100) while True: # 截取游戲區域 region_screenshot = pyautogui.screenshot(region=game_region) # 檢測紅色方塊出現 if pyautogui.pixelMatchesColor(500, 250, (255, 0, 0)): pyautogui.press("space") # 按空格鍵得分
案例 3:批量重命名文件
場景:將文件夾中的 100 張圖片按規則重命名。
import os
import pyautogui # 打開文件資源管理器
os.system("explorer.exe .\\images")
time.sleep(2) # 依次重命名文件
for i in range(1, 101): pyautogui.hotkey("ctrl", "a") # 全選文件 pyautogui.press("f2") # 重命名 pyautogui.write(f"photo_{i:03d}") # 格式化名稱(photo_001) pyautogui.press("enter") time.sleep(0.5)
擴展思考
1. PyAutoGUI 與其他工具的結合
- 與 Selenium 結合:
# 用 Selenium 處理網頁,PyAutoGUI 處理下載彈窗 driver.get("https://example.com/download") pyautogui.press("enter") # 自動確認下載對話框
- 打包為可執行文件:
pip install pyinstaller pyinstaller --onefile your_script.py
2. 安全性和法律合規性
- 風險提示:
- 避免自動化操作金融交易、社交賬號等敏感場景
- 部分軟件(如游戲)可能禁止自動化腳本
- 合規建議:
- 僅用于個人效率提升或授權場景
- 遵守《計算機軟件保護條例》和平臺規則
總結
通過本實戰,你已掌握:
- PyAutoGUI 的核心操作(鼠標、鍵盤、圖像識別)
- 復雜任務的異常處理與調試技巧
- 從表單填寫到游戲模擬的完整案例
- 自動化腳本的法律邊界與安全實踐
下集預告:
《No25: Python 并發編程:從多線程到異步 IO》將帶你突破單線程性能瓶頸,實現高并發任務處理!
附:運行環境
- 環境要求:Python 3.7+、Windows/macOS/Linux