注:pyautogui 只是能够控制鼠标和键盘事件,并不能提取屏幕中的文本信息
# 依赖安装
# 快速上手
| import pyautogui |
| |
| |
| |
| print(pyautogui.size()) |
| |
| |
| print(pyautogui.position()) |
| |
| |
| print(pyautogui.onScreen(1920, 100)) |
# 鼠标控制
| |
| screenX, screenY = pyautogui.size() |
| |
| |
| pyautogui.moveTo(screenX / 2, screenY / 2, duration=1) |
| |
| |
| pyautogui.moveRel(100, 0, duration=0.5) |
| pyautogui.moveRel(0, -200, duration=0.5) |
| pyautogui.moveRel(100, -200, duration=0.5) |
| |
| |
| pyautogui.click(button='right') |
| |
| |
| pyautogui.click(100, 100, clicks=3, interval=0.1, duration=0.5) |
| |
| |
| pyautogui.click(100, 100, button='right', clicks=2, interval=0.5, duration=0.2) |
| |
| |
| pyautogui.dragTo(screenX / 2, screenY / 2) |
| |
| |
| pyautogui.dragRel(-100, 200, duration=0.5, button='right') |
# 键盘控制
| |
| |
| pyautogui.typewrite('A') |
| pyautogui.typewrite('hello, PyAutoGUI!\n') |
| |
| |
| pyautogui.press(['p', 'y', ' '], interval=0.1) |
| pyautogui.typewrite(['capslock', 'p', 'y'], interval=0.1) |
| |
| |
| pyautogui.hotkey('shift', 'shift', 'esc', interval=0.1) |
# 消息窗口
| pyautogui.alert(text='警告', title='PyAutoGUI消息框', button='OK') |
| pyautogui.confirm(text='请选择', title='PyAutoGUI消息框', buttons=['1', '2', '3']) |
| txt = pyautogui.prompt(text='请输入', title='PyAutoGUI消息框', default='请输入') |
| pwd = pyautogui.password(text='输入密码', title='PyAutoGUI消息框', default='', mask='*') |
# 截图
| |
| |
| pyautogui.screenshot('shot.png', region=(1000, 600, 600, 400)) |
# 通过按钮图片定位按钮位置
前提:需要安装 opencv-python
依赖
| import pyautogui |
| import cv2 |
| import numpy as np |
| |
| |
| def get_img_button_position(img_path): |
| """ |
| 获取按钮图片的在屏幕中的位置 |
| :param img_path: 按钮图片路径 |
| :return: 按钮图片的中心位置 |
| """ |
| template = cv2.imread(img_path, 0) |
| w, h = template.shape[::-1] |
| |
| screenshot = pyautogui.screenshot() |
| screenshot_np = np.array(screenshot) |
| screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY) |
| |
| res = cv2.matchTemplate(screenshot_gray, template, cv2.TM_CCOEFF_NORMED) |
| threshold = 0.8 |
| loc = np.where(res >= threshold) |
| |
| for pt in zip(*loc[::-1]): |
| cv2.rectangle(screenshot_np, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2) |
| |
| |
| |
| |
| button_center = (pt[0] + w // 2, pt[1] + h // 2) |
| print(f"Button center: {button_center}") |
| return button_center |
| |
| |
| |
| button_position = get_img_button_position('./data/kais.png') |
| pyautogui.moveTo(*button_position, duration=0.5) |
| pyautogui.click(clicks=1) |
# 获取当前鼠标位置技巧
运行以下代码,将光标固定在 input 输入后面,再将鼠标移动到目标点,回车,控制台就会输出目标的坐标
| for i in range(10): |
| input("当前坐标:") |
| print(pyautogui.position()) |