PyAutoGUI快速入门指南(5)
屏幕截图
PyAutoGUI
使用 Pillow/PIL
处理图像数据。在Linux
上,需要执行sudo apt-get install scrot
以使用屏幕截图功能。
>>> pyautogui.screenshot() # returns a Pillow/PIL Image object
<PIL.Image.Image image mode=RGB size=1920x1080 at 0x24C3EF0>
>>> pyautogui.screenshot('foo.png') # returns a Pillow/PIL Image object, and saves it to a file
<PIL.Image.Image image mode=RGB size=1920x1080 at 0x31AA198>
如果有要单击的图像文件,可以在屏幕上使用locateOnScreen()
找到它。locateOnScreen()
返回值分别是(left, top, width, height)
。
>>> pyautogui.locateOnScreen('looksLikeThis.png') # returns (left, top, width, height) of first place it is found
(863, 417, 70, 13)
函数locateAllOnScreen()
将返回屏幕上找到的对应的所有位置,我们可以循环获取每个位置,或者转成list
:
>>> 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)]
有时候,我们仅仅想要单击某个元素,即获取改图片元素的中心就可以,LocateCenterOnScreen()
函数只返回屏幕上图像所在中心的XY
坐标:
>>> pyautogui.locateCenterOnScreen('looksLikeThis.png') # returns center x and y
(898, 423)
如果在屏幕上找不到图像,这些函数将返回None
。
Note:图像定位函数的速度很慢,可能需要整整一两秒钟。