🔥PC端自动化测试实战教程-12-pywinauto对窗口和控件进行截图(详细教程)

215 阅读4分钟

1.简介

在宏哥之前的web端或者手机端做自动化过程中时经常会遇到一些截图操作,那么在做PC端的时候,是不是也会有截图操作,那么在PC端pywinauto应该怎么进行截图呢?宏哥今天就来将这个PC端截图的知识点讲解和分享一下。

2.截图方法

在pywinauto中存在自带的截图函数 capture_as_image() ,源码如下:

    def capture_as_image(self, rect=None):
        """
        Return a PIL image of the control.

        See PIL documentation to know what you can do with the resulting
        image.
        """
        control_rectangle = self.rectangle()
        if not (control_rectangle.width() and control_rectangle.height()):
            return None

        # PIL is optional so check first
        if not ImageGrab:
            print("PIL does not seem to be installed. "
                  "PIL is required for capture_as_image")
            self.actions.log("PIL does not seem to be installed. "
                             "PIL is required for capture_as_image")
            return None

        if rect:
            control_rectangle = rect

        # get the control rectangle in a way that PIL likes it
        width = control_rectangle.width()
        height = control_rectangle.height()
        left = control_rectangle.left
        right = control_rectangle.right
        top = control_rectangle.top
        bottom = control_rectangle.bottom
        box = (left, top, right, bottom)

        # check the number of monitors connected
        if (sys.platform == 'win32') and (len(win32api.EnumDisplayMonitors()) > 1):
                hwin = win32gui.GetDesktopWindow()
                hwindc = win32gui.GetWindowDC(hwin)
                srcdc = win32ui.CreateDCFromHandle(hwindc)
                memdc = srcdc.CreateCompatibleDC()
                bmp = win32ui.CreateBitmap()
                bmp.CreateCompatibleBitmap(srcdc, width, height)
                memdc.SelectObject(bmp)
                memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)

                bmpinfo = bmp.GetInfo()
                bmpstr = bmp.GetBitmapBits(True)
                pil_img_obj = Image.frombuffer('RGB',
                                               (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                                               bmpstr,
                                               'raw',
                                               'BGRX',
                                               0,
                                               1)
        else:
            # grab the image and get raw data as a string
            pil_img_obj = ImageGrab.grab(box)

        return pil_img_obj

由上边的截图方法,我们可以知道这个方法返回一个:控件的PIL图像 。因此我们需要安装PIL。

3.项目实战(窗口截图)

因为宏哥的系统是Windows11,所以这里为了减少不必要的麻烦主要还是通过Windows安装的Notepad++编辑器进行演示和实践。

3.1测试场景

1.今天演示的场景灰常简单,大致测试场景:启动电脑安装的Notepad++编辑器,然后对编辑器的窗口进行截图保存即可。

2.由宏哥介绍前边的截图方法,我们知道需要安装PIL模块,宏哥这里没有安装看看会不会报错。如下图所示:

3.安装PIL模块。命令行:pip install Pillow ,如下图所示:

3.2代码设计

3.3参考代码

# -*- coding:utf-8 -*-

# 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行

# 2.注释:包括记录创建时间,创建人,项目名称。
'''
Created on 2025-05-27
@author: 北京-宏哥
北京宏哥(微信搜索:北京宏哥,关注宏哥,提前解锁更多测试干货!)
Project: PC端自动化测试实战教程-12-pywinauto对窗口和控件进行截图(详细教程)
'''

# 3.导入模块
from pywinauto import Application
import time

app = Application('uia').start(r"D:/software/Notepad/Notepad++/notepad++.exe")
win = app['新文件 1 - Notepad++']
# 对窗口截图
win.capture_as_image().save('Notepad++.png')

3.4运行代码

1.运行代码,右键Run'Test',就可以看到控制台输出,如下图所示:

2.运行代码后电脑端的动作(启动Notepad++编辑器,并截图)。如下图所示:

3.查看窗口截图,我们可以发现:截图会有其它窗口的背景会叠加,如下图所示:

4.项目实战(控件截图)

因为宏哥的系统是Windows11,所以这里为了减少不必要的麻烦主要还是通过Windows安装的Notepad++编辑器进行演示和实践。

4.1测试场景

1.今天演示的场景灰常简单,大致测试场景:启动电脑安装的Notepad++编辑器,然后对编辑器的菜单栏控件进行截图保存即可。

2.由于前边已经将所需的环境安装好了,这里就可以直接用了。

4.2代码设计

4.3参考代码

# -*- coding:utf-8 -*-

# 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行

# 2.注释:包括记录创建时间,创建人,项目名称。
'''
Created on 2025-05-27
@author: 北京-宏哥
北京宏哥(微信搜索:北京宏哥,关注宏哥,提前解锁更多测试干货!)
Project: PC端自动化测试实战教程-12-pywinauto对窗口和控件进行截图(详细教程)
'''

# 3.导入模块
from pywinauto import Application
import time

app = Application('uia').start(r"D:/software/Notepad/Notepad++/notepad++.exe")
win = app['新文件 1 - Notepad++']
time.sleep(5)
# 对菜单栏控件截图
menu = win.child_window(title="应用程序", auto_id="MenuBar", control_type="MenuBar")
time.sleep(5)
menu.capture_as_image().save('menu.png')

4.4运行代码

1.运行代码,右键Run'Test',就可以看到控制台输出,如下图所示:

2.运行代码后电脑端的动作(启动Notepad++编辑器,并截图)。如下图所示:

3.查看控件截图,我们可以发现:截图好像不太全,感觉就像截了一半。查了资料说与电脑屏幕分别率有关系,有的说是因为没有加载完成,就截图了,但是宏哥加了等待后,前后对比也是没有去别的,如下图所示:

5.小结

5.1注意事项‌

  1. ‌Backend选择‌
    推荐优先使用backend="uia"(支持更多现代应用),若控件无法识别可切换至backend="win32"
  2. ‌窗口激活状态‌
    capture_as_image()要求窗口可见且未被完全遮挡,否则可能截取失败。
  3. ‌分辨率适配‌
    高DPI屏幕需设置应用缩放兼容性模式,避免截图坐标偏移。

好了,时间不早了,今天就分享到这里吧!!!