python+pyautogui—PC端自动化(一)截屏及数据获取

官网:Roadmap — PyAutoGUI documentation

1、设置等待延时

# 可用来调试使用。每次公共函数调用后暂停的秒数,默认为0.1
pyautogui.PAUSE = 2

2、获取屏幕分辨率

w, h = pyautogui.size()
print(w, h)   # 1920 1080

3、获取进程号

# 根据运行程序窗口名返回对应的进程号
print(pyautogui.getWindowsWithTitle('Navicat Premium'))   
### >>> [Win32Window(hWnd=200338)]

# 查询所有正在运行的进程号
print(pyautogui.getAllWindows())
### >>> [Win32Window(hWnd=65700), Win32Window(hWnd=66430), Win32Window(hWnd=65806), Win32Window(hWnd=4458502), Win32Window(hWnd=264340), Win32Window(hWnd=1180704), Win32Window(hWnd=526736), Win32Window(hWnd=459014), Win32Window(hWnd=263444), Win32Window(hWnd=196756), Win32Window(hWnd=198426), Win32Window(hWnd=327760), Win32Window(hWnd=721494), Win32Window(hWnd=131232), Win32Window(hWnd=65944), Win32Window(hWnd=65964), Win32Window(hWnd=65972), Win32Window(hWnd=65896), Win32Window(hWnd=65894), Win32Window(hWnd=132098), Win32Window(hWnd=985504), Win32Window(hWnd=200338), Win32Window(hWnd=921376), Win32Window(hWnd=460248), Win32Window(hWnd=131380)]

4、检测像素点

如果要检验指定位置的一点的像素值,可以用pixelMatchesColor(x,y,RGB)函数,若所在屏幕中(x,y)点的实际RGB三色与函数中的RGB一样就会返回True,否则返回False,olerance参数可以指定红、绿、蓝3种颜色误差范围

print(pyautogui.pixelMatchesColor(500, 300, (43, 43, 43)))
print(pyautogui.pixelMatchesColor(500, 300, (50, 255, 245), tolerance=10))

5、截屏操作

①截屏保存

截取全屏

im = pyautogui.screenshot('screenshot1.png') 
print(im)  # 打印图片的属性

截取指定位置的图片:截取区域region参数为——左上角XY坐标值、宽度和高度

pyautogui.screenshot('screenshot2.png', region=(0, 0, 500, 800))

②获取截图文件在屏幕上的位置

获得文件图片在现在的屏幕上面的坐标,返回的是一个元组(x,y,width,height),如果截图没找到,pyautogui.locateOnScreen()函数返回None,可选的confidence关键字参数指定函数在屏幕上定位图像的精度。这是有帮助的情况下,函数无法定位图像由于可忽略的像素差异

a = pyautogui.locateOnScreen('423.png', confidence=0.9)
print(a)  # 打印结果:Box(left=1693, top=817, width=151, height=147)

获得文件图片在现在的屏幕上面的中心坐标

# .center()获得文件图片在现在的屏幕上面的中心坐标,括号中分别传递,图片的X轴,Y轴,宽,长,打印结果:Point(x=1768, y=890)
print(pyautogui.center(a))  
# 获得文件图片在现在的屏幕上面的中心坐标,括号中分别传递,图片的X轴,Y轴,宽,长,效果同.center()
b = pyautogui.locateCenterOnScreen('423.png')  
print(b)  # 打印结果:Point(x=1768, y=890)

③获取屏幕所有与目标图片匹配的对象

从左上角原点开始向右向下搜索截图位置:
locateOnScreen(image, grayscale=False):返回找到的第一个截图Image对象在屏幕上的坐标(left, top, width, height),如果没找到返回None
locateCenterOnScreen(image, grayscale=False):返回找到的第一个截图Image对象在屏幕上的中心坐标(x, y),如果没找到返回None
locateAllOnScreen(image, grayscale=False):返回找到的所有相同截图Image对象在屏幕上的坐标(left, top, width, height)的生成器
locate(needleImage, haystackImage, grayscale=False):返回找到的第一个截图Image对象在haystackImage里面的坐标(left, top, width, height),如果没找到返回None
locateAll(needleImage, haystackImage, grayscale=False):返回找到的所有相同截图Image对象在haystackImage里面的坐标(left, top, width, height)的生成器
# 可以用for循环和list()输出
pyautogui.locateAllOnScreen('20.png')  # 结果为列表,可通过循环遍历
### >>> [[Box(left=1267, top=845, width=157, height=167)]]

你可能感兴趣的:(自动化测试,图像处理,自动化)