记pyautogui使用方法

2022-10-15,

记录学习过程,本人喜欢简洁不啰嗦:

控制鼠标

 1 pyautogui.moveTo(w - 100, h - 100, duration=0.25)  # 立即移动到指定x, y位置坐标, duration表示移动花费的时间,0表示立即
2 pyautogui.moveRel(100, 0, duration=0.25) # 在当前位置移动
3 pyautogui.position() # 获取鼠标当前位置
4 pyautogui.dragTo() # 鼠标左键移动
5 pyautogui.dragRel() # 鼠标右键移动
6 pyautogui.click(100, 150, button='right') # 默认左键 left | right
7 pyautogui.mouseDown(476, 239) # 指定按键按下
8 pyautogui.mouseUp(476, 100) # 指定按键松开
9 pyautogui.doubleClick(100, 230) #左键双击
10 pyautogui.rightClick(1000, 200) # 鼠标右键单击
11 pyautogui.middleClick(100, 200) # 鼠标中键单击
12 pyautogui.scroll(200) # 滚轮滚动, 整数向上滚动,负数向下滚动
13
14 dragRel方法小示例:
15 time.sleep(3)
16 pyautogui.click()
17 dis = 200
18 while dis > 0:
19 pyautogui.dragRel(dis, 0, duration=0.1)
20 dis -= 5
21 pyautogui.dragRel(0, dis, duration=0.1)
22 pyautogui.dragRel(-dis, 0, duration=0.1)
23 dis -= 5
24 pyautogui.dragRel(0, -dis, duration=0.1)

图片处理

1 img = pyautogui.screenshot()     # 屏幕快照
2 img.getpixel((50, 200)) # 得到图片坐标 RGB
3 pyautogui.pixelMatchesColor(50, 200, (200, 100, 100)) # 匹配当前屏幕颜色 True | False & 宽,高,RGB颜色
4 pyautogui.locateCenterOnScreen(img) # 返回图片中心坐标
5 pyautogui.locateOnScreen(img) # 完全匹配图片,未找到返回None
6 pyautogui.locateAllOnScreen(img) # 返回匹配多处不同的值 [Box(left=0, top=0, width=1920, height=1080)]

控制键盘

1 pyautogui.typewrite('hello python', 0.25)     # 文本框输入内容,需要先确定焦点
2 pyautogui.typewrite(['a', 'b', 'left', 'left', 'X', 'Y']) #参考PyKeyboard属性表
3 pyautogui.keyDown('shift') # 按下某个键
4 pyautogui.press('4') # 输入内容
5 pyautogui.keyUp('shift') # 松开按键
6 pyautogui.hotkey('ctrl', 'c') # 组合键

其他方法

1 import pyautogui    # 导入模块
2 pyautogui.PAUSE = 1 # 每次调用函数后暂停1秒
3 pyautogui.FAILSAFE = True # 自动防故障
4 x,y = pyautogui.size() # 获取x、y坐标

记pyautogui使用方法的相关教程结束。

《记pyautogui使用方法.doc》

下载本文的Word格式文档,以方便收藏与打印。