Python PyAutoGUI 详细教程
Python PyAutoGUI 详细教程
Python PyAutoGUI 详细教程
PyAutoGUI 是一个用于 GUI 自动化的跨平台库,可以控制鼠标的移动、点击以及键盘的敲击等操作,适用于 Windows、macOS 和 Linux 系统。本文将详细介绍如何使用 PyAutoGUI 进行基本的 GUI 自动化任务。
安装 PyAutoGUI
首先需要在你的系统中安装 Python(推荐 Python 3.6+),然后通过 pip 来安装 PyAutoGUI:
pip install pyautogui
基本用法
当前鼠标的信息
pyautogui.mouseInfo()
弹出如下窗口,各属性会跟随鼠标的移动而变化。
获取窗体
win = pyautogui.getActiveWindow() # 返回对象 Win32Window,当前活动窗体
title = pyautogui.getActiveWindowTitle() # 返回活动窗体名称
winat = pyautogui.getWindowsAt(800, 600) # 返回对象列表,在指定位置上打开的窗体
wins = pyautogui.getAllWindows() # 返回所有窗体
titles = pyautogui.getAllTitles() # 返回字符串列表,包含所有窗体的标题
win_t = pyautogui.getWindowsWithTitle("ag_test") # 返回对象列表,标题中包含了指定字符串的所有窗体
屏幕相关
print(pyautogui.size()) # Size(width=1920, height=1080)
print(pyautogui.position()) # Point(x=661, y=377)
print(pyautogui.onScreen(960, 540)) # True
鼠标相关
pyautogui.mouseDown(960, 540) # 在指定位置按下鼠标
pyautogui.mouseUp(960, 540) # 在指定位置松开鼠标
pyautogui.click() # 左键单击
pyautogui.leftClick() # 左键单击
pyautogui.rightClick() # 右键单击
pyautogui.middleClick() # 中键(滚轮键)单击
pyautogui.doubleClick() # 左键双击
pyautogui.tripleClick() # 左键三击
pyautogui.scroll(100) # 向上滚动 100 像素
pyautogui.scroll(-100) # 向下滚动 100 像素
pyautogui.hscroll(100)
pyautogui.vscroll(100)
pyautogui.moveTo(800, 150) # 鼠标移动到指定位置
pyautogui.moveRel(160, 390) # 鼠标移动(按相对位置)
pyautogui.dragTo(800, 250, duration=2) # 拖动至坐标(800, 250),耗时2秒
pyautogui.dragRel(160, 390, duration=2) # 拖动至相对位置,正数表示向右下拖拽,负数则相反
键盘相关
print(pyautogui.isValidKey("|")) # True 是键盘可以敲出的单个字符
pyautogui.keyDown("|")
pyautogui.keyUp("|")
# 键盘按下指定字符(多个字符时需要转换成列表),总共按多少次,每次间隔多少秒 abcabcabcabcabc
pyautogui.press(list("abc"), 5, 0.5)
pyautogui.write("Hello", interval=0.5) # 键入指定字符串,每次间隔0.5秒
pyautogui.hotkey("ctrl", "shift", "c") # 模拟 Ctrl+Shift+C 快捷键
截屏相关
截取整个屏幕:
screenshot = pyautogui.screenshot()
screenshot.save('screenshot.png')
截取屏幕的一部分:
region = (100, 100, 300, 300) # (left, top, width, height)
part_screenshot = pyautogui.screenshot(region=region)
part_screenshot.save('part_screenshot.png')
其他方法
pyautogui.displayMousePosition() # 显示鼠标坐标和坐标点的RGB(在命令行中按Ctrl+C结束)
pyautogui.sleep(0.1) # 同 time.sleep()
pyautogui.printInfo() # 输出 getinfo() 的内容
实例:自动化网页填写表单
假设我们需要自动填写一个在线表单,流程如下:
import time
import webbrowser
import pyautogui
# 打开网页
webbrowser.open("https://example.com/login")
time.sleep(5) # 给页面加载时间
# 用户名和密码信息
username = "your_username"
password = "your_password"
# 位置数据可能需要根据实际情况调整
pyautogui.moveTo(300, 300)
pyautogui.click()
# 输入用户名
pyautogui.write(username)
# 移动到密码框
pyautogui.moveRel(0, 50)
pyautogui.click()
# 输入密码
pyautogui.write(password)
# 登录
pyautogui.press('enter')
以上代码演示了如何使用 PyAutoGUI 自动完成一些简单的任务。不过需要注意的是,实际应用中,元素的位置可能因为不同的显示器分辨率或窗口大小而不同,因此可能需要对坐标进行适当调整。
结语
PyAutoGUI 提供了丰富的功能来帮助我们实现各种 GUI 自动化需求。但请合理使用这些工具,确保它们被用于合法且道德的目的。希望这份指南能帮助你开始探索和利用 PyAutoGUI 的强大能力!
作者:逝去的紫枫