Python 桌面自动化操作指南
本文分享一套基于 Python 语言的自动化操作流程解决方案,涉及 pyautogui、pyperclip、pythoncom、win32com 依赖包。安装命令如下:
pip install pyautogui
pip install pyperclip
pip install pythoncom
pip install pywin32
核心模块说明
- pyautogui:自动化控制鼠标和键盘的 Python 模块。可执行移动光标、单击(左/右/中键)、截图、图像识别、获取鼠标位置等任务。
- pyperclip:在不同应用程序之间复制和粘贴文本数据,适用于不支持 Ctrl+C/V 操作的界面。
- pythoncom:允许 Python 程序与 COM 对象交互,实现创建、访问、调用(如访问 Microsoft Office 文档、操作 Windows 注册表)。
- win32com:与 pythoncom 类似,但提供更高级的功能和更易用的接口。
自动化操作流程实现
自动化流程类似于 RPA 机器人,首先需人工记录关键点击节点或操作步骤并截图保存。基于截图进行图像比对和相对坐标计算,模拟鼠标点击或键盘输入。
1. 窗口置顶处理
在模拟操作过程中,需确保目标应用程序始终为置顶状态,避免弹窗覆盖。以下代码获取当前所有应用程序句柄并找到待操作对象的句柄 hwnd,将其置顶。
import win32gui
import pythoncom
import win32com.client
import time
hwnd_title = {}
def get_all_hwnd(hwnd, hwnd_list):
if win32gui.IsWindowVisible(hwnd):
title = win32gui.GetWindowText(hwnd)
if title:
hwnd_title[hwnd] = title
hwnd_list.append(hwnd)
# 获取所有窗口句柄
hwnd_list = []
win32gui.EnumWindows(get_all_hwnd, hwnd_list)
for h, t in hwnd_title.items():
print(f"[{h}] {t}")
def setFront(hwnd):
pythoncom.CoInitialize()
shell = win32com.client.Dispatch("WScript.Shell")
# 使用 Alt+Tab 切换回前台(视具体场景调整)
shell.SendKeys('%')
win32gui.SetForegroundWindow(hwnd)
time.sleep(0.2)
pythoncom.CoUninitialize()
2. 定位与点击
进入应用程序界面后,通过图像识别或相对坐标定位待操作区域。
方法一:图像识别
import pyautogui
# im1 是应用程序界面截图,img 是待点击功能按钮截图
im1 = pyautogui.screenshot(region=(x, y, width, height))
# grayscale=True 开启灰度识别,confidence=0.7 为相似度阈值
loc = pyautogui.locate(img, im1, grayscale=True, confidence=0.7)
if loc:
x, y = pyautogui.center(loc)
setFront(hwnd)
pyautogui.click(x, y)
方法二:相对坐标
获取当前程序的坐标及宽高,在此基础上进行偏移量计算。
rect = win32gui.GetWindowRect(hwnd)
x_offset = rect[0]
y_offset = rect[1]
w = rect[2] - x_offset
h = rect[3] - y_offset
setFront(hwnd)
# 点击相对偏移位置
pyautogui.click(x_offset + relative_x, y_offset + relative_y)
3. 等待响应
如果应用程序正在响应,固定等待时间可能导致意外。可通过检测图像是否出现来判断。
def waitOccur(img, region, n=30, confidence=0.7):
"""
等待 img 出现在指定区域
:param img: 目标截图
:param region: 截图区域 (x, y, w, h)
:param n: 最大等待次数
:param confidence: 匹配置信度
:return: True 若找到,否则 False
"""
for i in range(n):
m1 = pyautogui.screenshot(region=region)
loc = pyautogui.locate(img, m1, grayscale=True, confidence=confidence)
if loc is not None:
return True
time.sleep(1)
return False
注意事项
- 窗口置顶:每次鼠标模拟点击前建议调用
setFront(hwnd),防止焦点丢失。 - 时间间隔:建议使用
time.sleep()设置较大的点击间隔,避免因程序响应过慢导致失效。 - 环境依赖:确保已安装
pywin32以支持win32gui和win32com模块。

