之前使用pywinauto来做UI自动化,其中也有鼠标键盘的操作,但是使用不是很方便。
所以查看了一下,发现pyautogui这个库,研究了一下,觉得这个库操作鼠标键盘比较方便。
看了官方文档,把基本的操作在此做个记录:
>>> import pyautogui
>>> pyautogui.position() # 当前鼠标的坐标
(968, 56)
>>> pyautogui.size() # 当前屏幕的大小,及分辨率
(1920, 1080)
>>> pyautogui.onScreen(x, y) # 如果x和y表示的坐标在屏幕范围内则返回True
True
鼠标功能:
>>> pyautogui.moveTo(x, y, duration=num_seconds) # 移动鼠标至xy坐标,duration是在多少秒内移动到xy坐标(这是绝对坐标),如果duration=0,或者不写就是直接移动到xy坐标处
>>> pyautogui.moveRel(xOffset, yOffset, duration=num_seconds) # 相对移动x和y,此处可以用move来替代moveRel
>>> pyautogui.dragTo(x, y, duration=num_seconds) # 拖动鼠标至xy坐标
>>> pyautogui.dragRel(xOffset, yOffset, duration=num_seconds) # 拖动鼠标x和y
>>> pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks, button='left') # 左键点击
>>> pyautogui.rightClick(x=moveToX, y=moveToY) # 右击 x和y是指在xy坐标处点击
>>> pyautogui.middleClick(x=moveToX, y=moveToY) # 点击中键
>>> pyautogui.doubleClick(x=moveToX, y=moveToY) # 双击左键
>>> pyautogui.tripleClick(x=moveToX, y=moveToY) # 三击左键
>>> pyautogui.scroll(amount_to_scroll, x=moveToX, y=moveToY) # 滚动滚轮
pyautogui.scroll(100) # 正数为向上滚动
pyautogui.scroll(-100) # 负数为向下滚动
>>> pyautogui.mouseDown(x=moveToX, y=moveToY, button='left') # 鼠标按下
>>> pyautogui.mouseUp(x=moveToX, y=moveToY, button='left') # 鼠标放开
键盘功能:
>>> pyautogui.typewrite('Hello world!\n', interval=secs_between_keys) # 输入Hello world!
>>> pyautogui.hotkey('ctrl', 'c') # ctrl-c
>>> pyautogui.hotkey('ctrl', 'v') # ctrl-v
>>> pyautogui.keyDown(key_name) # 单独按下一个键
>>> pyautogui.keyUp(key_name) # 单独放开一个键
消息对话框功能:
>>> pyautogui.alert('This displays some text with an OK button.')
>>> pyautogui.confirm('This displays text and has an OK and Cancel button.')
'OK'
>>> pyautogui.prompt('This lets the user type in a string and press OK.')
'This is what I typed in.'
截屏功能:
>>> pyautogui.screenshot('foo.png') # 全屏截图,保存为foo.png放在当前文件目录下
# 在界面上如果找不到图片,返回None。找到图片,返回(634,438)是图片左上角的坐标,后面是宽度和高度
>>> pyautogui.locateOnScreen('123.png')
Box(left=634, top=438, width=120, height=123)
# 返回图片中心的坐标
>>> pyautogui.locateCenterOnScreen('looksLikeThis.png')
(898, 423)
# 返回屏幕所以找到的图片的位置的生成器
>>> for i in pyautogui.locateAllOnScreen('looksLikeThis.png')
...
...
(863, 117, 70, 13)
(623, 137, 70, 13)
(853, 577, 70, 13)
(883, 617, 70, 13)
(973, 657, 70, 13)
(933, 877, 70, 13)
>>> list(pyautogui.locateAllOnScreen('looksLikeThis.png'))
[(863, 117, 70, 13), (623, 137, 70, 13), (853, 577, 70, 13), (883, 617, 70, 13), (973, 657, 70, 13), (933, 877, 70, 13)]