pyautogui 库

发布于 2024-07-08  413 次阅读


温馨提示:本文最后更新于2024年7月8日,已超过 30 天没有更新,某些文章具有时效性,若有错误或已失效,请在下方留言!

pyautogui 是一个用于控制鼠标和键盘的 Python 库,可以模拟用户的输入操作,如移动鼠标、点击鼠标、按键、输入文本等从而实现自动化任务。

1. 安装和导入

安装:pip install pyautogui

导入:import pyautogui

2. 基本功能

2.1 获取屏幕尺寸

screen_width, screen_height = pyautogui.size()
print(f"Screen width: {screen_width}, Screen height: {screen_height}")

2.2 获取鼠标位置

current_mouse_x, current_mouse_y = pyautogui.position()
print(f"Current mouse position: ({current_mouse_x}, {current_mouse_y})")

2.3 移动鼠标

# 移动鼠标到屏幕的中心
pyautogui.moveTo(screen_width / 2, screen_height / 2, duration=1)  # duration 参数指定移动的持续时间(秒)

2.4 点击鼠标

# 左键单击
pyautogui.click()

# 右键单击
pyautogui.click(button='right')

# 中键单击
pyautogui.click(button='middle')

2.5 输入文本

pyautogui.write('Hello, World!', interval=0.1)  # interval 参数指定每个字符之间的间隔时间(秒)

2.6 按键操作

# 按下并释放一个键
pyautogui.press('enter')

# 按下并保持一个键
pyautogui.keyDown('shift')
pyautogui.write('hello')
pyautogui.keyUp('shift')

2.7 截图

# 截取整个屏幕并保存
screenshot = pyautogui.screenshot()
screenshot.save('screenshot.png')

# 截取指定区域
region_screenshot = pyautogui.screenshot(region=(0, 0, 300, 400))  # x, y, width, height
region_screenshot.save('region_screenshot.png')

2.8 查找屏幕上的图像

# 找到图像在屏幕上的位置
button_location = pyautogui.locateOnScreen('button.png')
if button_location:
    print(f"Button found at: {button_location}")

# 找到图像中心的坐标
button_center = pyautogui.locateCenterOnScreen('button.png')
if button_center:
    print(f"Button center at: {button_center}")
    pyautogui.click(button_center)

3. 补充

pyautogui.FAILSAFE:为了防止脚本失控,pyautogui 在默认情况下启用一个 “紧急停止” 功能。如果将鼠标移到屏幕的左上角,pyautogui 会引发 pyautogui.FailSafeException 并停止执行。

pyautogui.PAUSE:你可以设置每个 pyautogui 函数调用后的暂停时间。例如,设置 pyautogui.PAUSE = 1 会在每个函数调用后暂停 1 秒。

pyautogui.FAILSAFE = True
pyautogui.PAUSE = 1

4. 完整示例

以下是一个完整的示例,将上述功能组合在一起:

import pyautogui

# 获取屏幕尺寸
screen_width, screen_height = pyautogui.size()
print(f"Screen width: {screen_width}, Screen height: {screen_height}")

# 获取鼠标位置
current_mouse_x, current_mouse_y = pyautogui.position()
print(f"Current mouse position: ({current_mouse_x}, {current_mouse_y})")

# 移动鼠标到屏幕的中心并点击
pyautogui.moveTo(screen_width / 2, screen_height / 2, duration=1)
pyautogui.click()

# 输入文本
pyautogui.write('Hello, World!', interval=0.1)

# 按下并释放回车键
pyautogui.press('enter')

# 截取整个屏幕并保存
screenshot = pyautogui.screenshot()
screenshot.save('screenshot.png')

5. 参考

  1. asweigart/pyautogui: A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard. (github.com)
  2. https://www.bilibili.com/video/BV1xb4y1S7S5

本文由 ChatGPT 撰写。

最后更新于 2024-07-08