大家好,今天咱们来聊一个真的很实用的Python库 —— PyAutoGUI。如果想在工作中偷懒,那这个库绝对能满足你的"懒"需求。
有了它,你可以让Python来控制你的鼠标和键盘,解放双手做更多有意义的事情(比如喝咖啡、刷视频😏)。
无论你是刚接触Python的新手,还是想给自己工作减负的Python玩家,这篇文章都能带你入门并学会一些真正能用的技巧。
简单来说,PyAutoGUI是一个让Python能控制鼠标和键盘的库,可以:
自动移动鼠标,点击,拖拽
自动键盘输入
截图,识别屏幕上的内容
实现各种自动化操作
最厉害的是,它跨平台(Windows、macOS、Linux都能用),安装也简单,一行命令搞定:
pip install pyautogui
在正式开始前,我们先来个简单栗子,感受一下它的威力!
import pyautogui
import time
# 给你3秒钟时间切换到记事本或其他输入窗口
time.sleep(3)
# 键盘输入
pyautogui.write('PyAutoGUI真好用!')
# 点击回车键
pyautogui.press('enter')
# 再写一行
pyautogui.write('这是我用Python写的~')
看到了吗?运行上面代码后,切换到任意可输入窗口,自动就输入了这两行文字。
不过要注意:程序运行后会马上控制你的鼠标键盘,所以我加了3秒延迟,给你切换窗口的时间。实在不行按Ctrl+C
中断程序。
PyAutoGUI能做各种鼠标操作,比如:
import pyautogui
# 1. 获取当前屏幕分辨率
width, height = pyautogui.size()
print(f"屏幕分辨率是:{width} x {height}")
# 2. 获取当前鼠标位置
x, y = pyautogui.position()
print(f"鼠标当前位置是:{x}, {y}")
# 3. 移动鼠标(绝对坐标)
pyautogui.moveTo(100, 100, duration=1) # 1秒内移动到(100, 100)位置
# 4. 移动鼠标(相对当前位置)
pyautogui.moveRel(50, 50, duration=0.5) # 从当前位置再向右下方移动(50, 50)
# 5. 鼠标点击
pyautogui.click() # 在当前位置单击左键
pyautogui.click(200, 200) # 在(200, 200)位置单击
pyautogui.rightClick(300, 300) # 右键点击
pyautogui.doubleClick() # 双击
# 6. 鼠标拖拽
pyautogui.dragTo(400, 400, duration=1) # 拖拽到绝对位置
pyautogui.dragRel(50, 0, duration=0.5) # 向右拖拽50像素
# 7. 鼠标滚轮
pyautogui.scroll(10) # 向上滚动10个单位
每个函数都很直观,参数也简单。duration
参数可以调整动作的速度,设为0就是瞬间完成,但我建议设个值,这样能看清发生了什么,也可以随时打断。
键盘操作同样简单,看看这些例子:
import pyautogui
import time
# 等几秒,让你有时间切换到文本编辑器
time.sleep(3)
# 1. 输入普通文本
pyautogui.write('Hello, PyAutoGUI!')
# 2. 按单个按键
pyautogui.press('enter') # 回车键
pyautogui.press('space') # 空格
pyautogui.press('backspace') # 退格
# 3. 按热键组合
pyautogui.hotkey('ctrl', 'a') # 全选
pyautogui.hotkey('ctrl', 'c') # 复制
pyautogui.press('right') # 按右方向键
pyautogui.hotkey('ctrl', 'v') # 粘贴
# 4. 按下和释放分开操作
pyautogui.keyDown('shift') # 按下shift
pyautogui.press('right') # 按右方向键(会选中文字)
pyautogui.press('right') # 再按一次
pyautogui.keyUp('shift') # 释放shift
常见的键名列表:
特殊键:enter
, esc
, space
, tab
, backspace
, delete
功能键:f1
到f12
方向键:up
, down
, left
, right
修饰键:ctrl
, alt
, shift
, win
PyAutoGUI不止能控制鼠标键盘,还能截图并分析图像:
import pyautogui
# 1. 截取整个屏幕
screenshot = pyautogui.screenshot()
# 保存截图
screenshot.save('my_screenshot.png')
# 2. 在屏幕上查找图片位置
try:
# 需要提前准备一个目标图片,比如start_button.png
position = pyautogui.locateOnScreen('start_button.png')
print(f"找到图片的位置:{position}")
# 获取图片中心点坐标
x, y = pyautogui.center(position)
# 点击该位置
pyautogui.click(x, y)
except:
print("没找到目标图片")
# 3. 获取指定位置的像素颜色
pixel_color = pyautogui.pixel(100, 100)
print(f"位置(100, 100)的颜色是:{pixel_color}")
图像识别很实用,但也挺挑剔。如果识别不到,可以尝试:
使用更清晰、更有特点的目标图片
调整屏幕分辨率或显示比例
用confidence
参数调整匹配精度:pyautogui.locateOnScreen('image.png', confidence=0.8)
(需要安装opencv-python)
import pyautogui
import time
def auto_fill_form():
# 数据准备
form_data = [
{"name": "张三", "phone": "13812345678", "address": "北京市海淀区"},
{"name": "李四", "phone": "13987654321", "address": "上海市浦东新区"},
# 可以继续添加更多数据
]
# 给3秒时间切换到表单页面
print("请在3秒内切换到表单页面...")
time.sleep(3)
for data in form_data:
# 输入姓名
pyautogui.write(data["name"])
pyautogui.press('tab') # 按Tab键跳到下一个输入框
# 输入电话
pyautogui.write(data["phone"])
pyautogui.press('tab')
# 输入地址
pyautogui.write(data["address"])
# 点击提交按钮(假设Tab再按一次到达提交按钮)
pyautogui.press('tab')
pyautogui.press('enter')
# 等待页面刷新,准备填写下一条
time.sleep(2)
if __name__ == "__main__":
auto_fill_form()
import pyautogui
import time
import random
def auto_clicker():
print("3秒后开始自动点击,按Ctrl+C停止")
time.sleep(3)
try:
click_count = 0
while True:
# 随机位置点击(在一个区域内)
x = random.randint(300, 500)
y = random.randint(400, 600)
# 移动并点击
pyautogui.moveTo(x, y, duration=0.1)
pyautogui.click()
click_count += 1
print(f"已点击 {click_count} 次")
# 随机等待一小段时间
time.sleep(random.uniform(0.5, 2.0))
except KeyboardInterrupt:
print("自动点击已停止")
if __name__ == "__main__":
auto_clicker()
import pyautogui
import time
from datetime import datetime
import os
def auto_screenshot(interval=60, total_shots=10, save_folder="screenshots"):
# 创建保存文件夹
if not os.path.exists(save_folder):
os.makedirs(save_folder)
print(f"将每隔{interval}秒截图一次,共{total_shots}次")
for i in range(total_shots):
# 获取当前时间作为文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{save_folder}/screen_{timestamp}.png"
# 截图并保存
screenshot = pyautogui.screenshot()
screenshot.save(filename)
print(f"第 {i+1}/{total_shots} 张截图已保存: {filename}")
# 最后一张不需要等待
if i < total_shots - 1:
time.sleep(interval)
print("截图任务完成!")
if __name__ == "__main__":
# 每30秒截图一次,共截5张
auto_screenshot(interval=30, total_shots=5)
自动化脚本可能会失控(比如无限循环点击),所以PyAutoGUI内置了几种安全措施:
import pyautogui
# 1. 启用故障保护(把鼠标移到屏幕左上角会触发异常并中断)
pyautogui.FAILSAFE = True # 默认就是开启的
# 2. 设置所有pyautogui函数执行后的间隔时间(秒)
pyautogui.PAUSE = 0.5 # 每执行一个动作后等待0.5秒
重要提示:如果脚本失控,立即把鼠标甩到屏幕左上角,或者按Ctrl+C
中断程序!
最后来个综合案例,做个自动签到工具:
import pyautogui
import time
import logging
from datetime import datetime
import os
# 设置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("auto_signin.log"),
logging.StreamHandler()
]
)
def auto_signin(target_image, retry_times=3, app_path=None):
"""
自动打开程序并签到
参数:
target_image: 签到按钮的截图
retry_times: 尝试次数
app_path: 应用程序路径(可选)
"""
try:
# 如果提供了应用路径,先启动应用
if app_path:
logging.info(f"正在启动应用: {app_path}")
os.startfile(app_path) # Windows系统适用
time.sleep(5) # 等待应用启动
# 查找并点击签到按钮
for attempt in range(retry_times):
logging.info(f"尝试第 {attempt+1}/{retry_times} 次查找签到按钮")
try:
# 查找图片位置
button_location = pyautogui.locateOnScreen(target_image, confidence=0.8)
if button_location:
# 获取中心点
button_x, button_y = pyautogui.center(button_location)
# 点击
logging.info(f"找到签到按钮,位置: ({button_x}, {button_y})")
pyautogui.click(button_x, button_y)
logging.info("签到成功!")
# 截图保存结果
time.sleep(1) # 等待签到结果显示
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
result_img = pyautogui.screenshot()
result_img.save(f"signin_result_{timestamp}.png")
logging.info(f"结果已保存为 signin_result_{timestamp}.png")
return True
else:
logging.warning("未找到签到按钮,将重试...")
time.sleep(2)
except Exception as e:
logging.error(f"查找或点击过程出错: {str(e)}")
logging.error(f"尝试 {retry_times} 次后仍未找到签到按钮")
return False
except Exception as e:
logging.error(f"自动签到过程发生错误: {str(e)}")
return False
if __name__ == "__main__":
# 使用示例
# 1. 准备好"签到按钮"的截图,比如 signin_button.png
# 2. 运行下面的代码
# 方式1:已经打开了应用,只需要查找并点击
auto_signin("signin_button.png")
# 方式2:自动打开应用再签到(Windows系统示例)
# auto_signin("signin_button.png", app_path="C:\\Path\\To\\App.exe")
使用时,需要先用截图工具截取签到按钮的图片,然后作为参数传入函数。
PyAutoGUI真的是个宝藏库,简单几行代码就能帮你解决很多重复性工作。但也有些注意事项:
环境差异:不同电脑分辨率、显示比例、系统版本可能导致识别失败
界面变化:网页或软件界面更新会导致脚本失效
安全风险:谨慎运行不明来源的自动化脚本
效率考虑:有些情况下,使用专业API可能比模拟鼠标键盘更高效
最后建议大家:先从简单的任务开始尝试,慢慢掌握后再挑战复杂场景。自动化的成就感真的很棒,一旦入门,你会发现更多可以偷懒的机会~
如果你对Python自动化感兴趣,可以点个关注,后面我们还会带来更多实用的Python小技巧!
【福利】 文末送个彩蛋,一个简单但实用的功能:定时提醒喝水小工具。
import pyautogui
import time
import datetime
def water_reminder(interval_mins=60):
"""每隔一段时间提醒喝水"""
print(f"喝水提醒已启动,将每隔{interval_mins}分钟提醒一次")
print("(程序运行中,按Ctrl+C退出)")
try:
count = 1
while True:
# 计算下次提醒时间
now = datetime.datetime.now()
next_time = now + datetime.timedelta(minutes=interval_mins)
print(f"下次提醒时间: {next_time.strftime('%H:%M:%S')}")
# 等待到达时间
time.sleep(interval_mins * 60)
# 弹出提醒
pyautogui.alert(
text=f'第{count}次提醒: 该喝水啦!补充水分更健康~',
title='喝水提醒',
button='好的'
)
count += 1
except KeyboardInterrupt:
print("喝水提醒已关闭,祝您健康每一天!")
if __name__ == "__main__":
# 每30分钟提醒一次
water_reminder(30)
示例中主要体现各种自动化操作实现,具体业务需要根据自身需求做修改哦~欢迎扫描下方二维码,添加逍遥,一起交流“偷懒”大法~~
喜欢就点个赞吧!我们下期再见~
转发、收藏、在看,是对作者最大的鼓励!👏
对Python,AI,自动化办公提效,副业发展等感兴趣的伙伴们,扫码添加逍遥,限免交流群
备注【成长交流】