python pyautogui库使用
- 在19年工作中, 遇到了一个问题,需要用到鼠标自动化操作的相关知识,本文章介绍下pyautogui的基本使用。pyautogui是一个操作鼠标键盘操作的库,里面的函数主要是完成自动化控制鼠标、键盘的功能。
1 基本函数
获取屏幕分辨率或者鼠标位置信息
# 当前屏幕的分辨率(宽度和高度)
pyautogui.size()
# 当前鼠标的坐标
pyautogui.position()
# 更为清楚的例子
# 获取当前屏幕分辨率
screenWidth, screenHeight = pyautogui.size()
# 获取当前鼠标位置
currentMouseX, currentMouseY = pyautogui.position()
# 两个值返回的是横竖上的值
鼠标移动以及点击
直接上例子
pyautogui.moveTo(125, 79, duration=0.2) # 从当前点移动到,x,y位置 duration为移动时间 最小值为0.1
pyautogui.moveTo(100, 200) # 下x,y为要移动的距离,moves mouse to X of 100, Y of 200.
pyautogui.click((125, 79))
>>> pyautogui.click(clicks=2) # double-click the left mouse button
>>> pyautogui.click(clicks=2, interval=0.25) # double-click the left mouse button, but with a quarter second pause in between clicks
>>> pyautogui.click(button='right', clicks=3, interval=0.25) ## triple-click the right mouse button with a quarter second pause in between clicks
>#clicks为点击次数,也可以用doubleClick
>>>pyautogui.doubleClick() # perform a left-button double click
moveTo与move的区别在于,moveTo中参数,x,y 为目标点,而move为移动的距离
鼠标拖拽
>>> pyautogui.dragTo(100, 200, button='left') # drag mouse to X of 100, Y of 200 while holding down left mouse button
>>> pyautogui.dragTo(300, 400, 2, button='left') # drag mouse to X of 300, Y of 400 over 2 seconds while holding down left mouse button
>>> pyautogui.drag(30, 0, 2, button='right') # drag the mouse left 30 pixels over 2 seconds while holding down the right mouse button
两者的区别与上一样,button则控制左击或者右击,‘right‘与’left‘
鼠标移动的补充
由于某种需要在鼠标move的过程中, 可能需要控制移动的速度
>>> pyautogui.moveTo(100, 100, 2, pyautogui.easeInQuad) # start slow, end fast
>>> pyautogui.moveTo(100, 100, 2, pyautogui.easeOutQuad) # start fast, end slow
>>> pyautogui.moveTo(100, 100, 2, pyautogui.easeInOutQuad) # start and end fast, slow in middle
>>> pyautogui.moveTo(100, 100, 2, pyautogui.easeInBounce) # bounce at the end
>>> pyautogui.moveTo(100, 100, 2, pyautogui.easeInElastic) # rubber band at the end
该库的文档中说明了easeInElastic可以自定义,在笔者并不清楚如何自定义,如果要定义自己的移动速度,可以自己通过move去实现,控制每次x,y的距离即可(曾经尝试过用这个方式去实现自动解决拖拽,但失败了)
mouseDown and mouseUp
>>> pyautogui.mouseDown(); pyautogui.mouseUp() # does the same thing as a left-button mouse click
>>> pyautogui.mouseDown(button='right') # press the right button down
>>> pyautogui.mouseUp(button='right', x=100, y=200) # move the mouse to 100, 200, then release the right button up.
如代码,鼠标按下及放开。
滚轮
>>> pyautogui.scroll(10) # scroll up 10 "clicks"
>>> pyautogui.scroll(-10) # scroll down 10 "clicks"
>>> pyautogui.scroll(10, x=100, y=100) # move mouse cursor to 100, 200, then scroll up 10 "clicks"
2 键盘操作
可以实现自动敲击键盘
# pyautogui.typewrite("hello word!") #发送键值 往框里输入值 只能是英文(数字笔者未尝试)
# pyautogui.hotkey("win","r") #热键 ,同时按下
#pyautogui.press("win") #相当于keyDown + keyUp二个函数的整合 按下某个键
# pyautogui.hotkey('alt','tab')
若要粘贴中文可以尝试如下操作
pyperclip.copy('和谐嘉园东苑')
pyperclip.paste() # 发现不起作用
pyautogui.hotkey('ctrl' + 'v') # 发现不起作用
pyautogui.keyDown('ctrl')
pyautogui.press('v')
pyautogui.keyUp('ctrl')
其它操作可以看操作文档
pyautogui操作文档
欢迎指正!谢谢