9

安利下这个库,PyAUtoGUI,自动化控制鼠标键盘

 3 years ago
source link: https://foofish.net/python-pyautogui.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PyAutoGUI 不知道你有没有用过,它是一款用Python自动化控制键盘、鼠标的库。但凡是你不想手动重复操作的工作都可以用这个库来解决。

比如,我想半夜时候定时给发个微信,或者每天自动刷页面等操作,它能完全模拟手动操作,而你可以安心的刷剧了。

嗯,懒惰是程序员的美德。

安装pyautogui

pip install pyautogui

键盘鼠标控制

>>> import pyautogui
>>> screenWidth, screenHeight = pyautogui.size() # 返回屏幕分辨率
>>> currentMouseX, currentMouseY = pyautogui.position() # 返回鼠标的所在位置
>>> pyautogui.moveTo(100, 150) #移动鼠标到指定位置
>>> pyautogui.click() # 单击
>>> pyautogui.click(200, 220) # 单击指定位置
>>> pyautogui.move(None, 10)  # 移动鼠标10个像素
>>> pyautogui.doubleClick() # 双击鼠标
>>> pyautogui.write('Hello world!', interval=0.25)  # 输入字符串,每个字符停留时间0.25秒
>>> pyautogui.press('esc') # 退出键
>>> pyautogui.keyDown('shift')  # Shitf键盘
>>> pyautogui.hotkey('ctrl', 'c')  # 组合键

用pyautogui自动画图

pyautogui.png

显示消息盒子

除了可以控制鼠标键盘外,还可以调用系统弹窗

>>> import pyautogui
>>> pyautogui.alert('This is an alert box.')
'OK'
>>> pyautogui.confirm('Shall I proceed?')
'Cancel'
>>> pyautogui.confirm('Enter option.', buttons=['A', 'B', 'C'])
'B'
>>> pyautogui.prompt('What is your name?')
'Al'
>>> pyautogui.password('Enter password (text will be hidden)')
'swordfish'
微信截图_20200814174232.png

通过窗口消息盒子可以实现一些简单的人机交互,比如某些地方需要人工输入内容时,这样可以接受用户的指令。

截图是使用的Pillow模块实现的,截图的用处在于通过图片识别技术识别图片内容,然后通过内容精准定位到某个元素的位置,实现精准点击。

>>> import pyautogui
>>> im1 = pyautogui.screenshot()
>>> im1.save('my_screenshot.png')
>>> im2 = pyautogui.screenshot('my_screenshot2.png')

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK