Windows GUI自动化控制工具之python uiAutomation

这篇具有很好参考价值的文章主要介绍了Windows GUI自动化控制工具之python uiAutomation。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

对 Windows GUI进行自动化控制的工具有很多,比如pywinauto、pyautogui、pywin32、Autoit、airtest、UIAutomation等,UI Automation API是微软提供的自动化框架,可在支持 Windows Presentation Foundation (WPF) 的所有操作系统上使用,支持的应用类型更多。本文介绍封装了UI Automation API的Python uiautomation 模块的使用方法。

Python uiautomation 模块由yinkaisheng 开发,封装了微软 UI Automation API,支持自动化Win32,MFC,WPF,Modern UI(Metro UI), Qt, IE, Firefox, Chrome和基于Electron开发的应用程序。

环境准备

uiautomation安装

最新版uiautomation2.0只支持Python 3版本,但不要使用3.7.6和3.8.1这两个版本,因为comtypes包在这两个版本中不能正常工作。

pip安装uiautomation:

$ pip install uiautomation

检查是否安装成功:

$ pip list | findstr uiautomation
uiautomation       2.0.18

安装完成后,在Python的Scripts(我的路径为C:\Program Files\Python37\Scripts)目录中会有一个文件automation.py,是用来枚举控件树结构的一个脚本。

可运行 automation.py -h查看命令帮助:

$ python automation.py -h
UIAutomation 2.0.18 (Python 3.7.2, 64 bit)
usage
-h      show command help
-t      delay time, default 3 seconds, begin to enumerate after Value seconds, this must be an integer
        you can delay a few seconds and make a window active so automation can enumerate the active window
-d      enumerate tree depth, this must be an integer, if it is null, enumerate the whole tree
-r      enumerate from root:Desktop window, if it is null, enumerate from foreground window
-f      enumerate from focused control, if it is null, enumerate from foreground window
-c      enumerate the control under cursor, if depth is < 0, enumerate from its ancestor up to depth
-a      show ancestors of the control under cursor
-n      show control full name, if it is null, show first 30 characters of control's name in console,
        always show full name in log file @AutomationLog.txt
-p      show process id of controls

if UnicodeError or LookupError occurred when printing,
try to change the active code page of console window by using chcp or see the log file @AutomationLog.txt
chcp, get current active code page
chcp 936, set active code page to gbk
chcp 65001, set active code page to utf-8

examples:
automation.py -t3
automation.py -t3 -r -d1 -m -n
automation.py -c -t3

进程查看器

对 Windows GUI进行自动化控制需要使用进程查看器工具对GUI界面元素进行定位,定位工具有很多,这里推荐使用微软提供的inspect.exe 或者 Accessibility Insights 这两款工具。

inspect.exe

inspect.exe 是 Windows SDK 自带的一个进程查看器,可以用来查看系统正在运行的进程信息、模块、线程、堆栈跟踪等详细数据。

Windows SDK下载地址为:https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/

建议直接到这里下载inspect.exe:https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/tree/master/inspect

64位系统版本的inspect.exe也可以点击这里下载。

Accessibility Insights

Accessibility Insights 是微软开发的一款辅助功能测试工具。它可以帮助开发者测试 web 应用、Windows 桌面应用和 Android 应用的可访问性,确保这些应用程序符合无障碍标准。

Accessibility Insights获取的控件属性信息没有inspect.exe全面,使用起来更加流畅。下载为:https://accessibilityinsights.io/downloads/

控件对象模型

微软 UIAutomation API定义了支持的控件类型和对应的模型(Pattern),所有支持的控件类型可参考:https://learn.microsoft.com/en-us/windows/win32/winauto/uiauto-controlpatternmapping

控件类型 必须支持的模型 可选模型 Does not support
Button None ExpandCollapse, Invoke, Toggle, Value None
Calendar Grid, Table Scroll, Selection Value
CheckBox Toggle None None
Edit None RangeValue, Text, Value None
List None Grid, MultipleView, Scroll, Selection Table
ListItem SelectionItem CustomNavigation, ExpandCollapse, GridItem, Invoke, ScrollItem, Toggle, Value None
Menu None None None
MenuBar None Dock, ExpandCollapse, Transform None
MenuItem None ExpandCollapse, Invoke, SelectionItem, Toggle None
RadioButton SelectionItem None Toggle
SplitButton ExpandCollapse, Invoke None None
Tab Selection Scroll None
TabItem SelectionItem None Invoke
Table Grid, GridItem, Table, TableItem None None
Text None GridItem, TableItem, Text Value
TitleBar None None None
ToolBar None Dock, ExpandCollapse, Transform None

python uiautomation库对UIAutomation API定义的各个Control和Pattern进行了封装。

下面来看使用python uiautomation操作Windows自带计算器的例子。

uiautomation库示例

控制计算器

可以使用inspect.exe来定位计算器元素:

python uiautomation,自动化测试,自动化,python,uiautomation,windows gui 自动化

示例脚本如下:

import os
import uiautomation as auto
import subprocess

class uiautoCalc(Loggers):
    """uiautomation控制计算器
    """
    def __init__(self):
        super().__init__()
        self.logger = Loggers().myLogger()
        auto.uiautomation.DEBUG_SEARCH_TIME =True 
        auto.uiautomation.SetGlobalSearchTimeout(2) # 设置全局搜索超时时间
        self.calcWindow = auto.WindowControl(searchDepth=1, Name='计算器', desc='计算器窗口') # 计算器窗口
        if not self.calcWindow.Exists(0,0):
            subprocess.Popen('calc')# 设置窗口前置
            self.calcWindow = auto.WindowControl(
            searchDepth=1, Name='计算器', desc='计算器窗口')
        self.calcWindow.SetActive() # 激活窗口
        self.calcWindow.SetTopmost(True) # 设置为顶层

    def gotoScientific(self):
        self.calcWindow.ButtonControl(AutomationId='TogglePaneButton', desc='打开导航').Click(waitTime=0.01)        
        self.calcWindow.ListItemControl(AutomationId='Scientific', desc='选择科学计算器').Click(waitTime=0.01)
        clearButton = self.calcWindow.ButtonControl(AutomationId='clearEntryButton', desc='点击CE清空输入')
        if clearButton.Exists(0,0):
            clearButton.Click(waitTime=0)
        else:
            self.calcWindow.ButtonControl(AutomationId='clearButton', desc='点击C清空输入').Click(waitTime=0.01)

    def getKeyControl(self):
        automationId2key ={'num0Button':'0','num1Button':'1','num2Button':'2','num3Button':'3','num4Button':'4','num5Button':'5','num6Button':'6','num7Button':'7','num8Button':'8','num9Button':'9','decimalSeparatorButton':'.','plusButton':'+','minusButton':'-','multiplyButton':'*','divideButton':'/','equalButton':'=','openParenthesisButton':'(','closeParenthesisButton':')'}        
        calckeys = self.calcWindow.GroupControl(ClassName='LandmarkTarget')
        keyControl ={}
        for control, depth in auto.WalkControl(calckeys, maxDepth=3):
            if control.AutomationId in automationId2key:
                self.logger.info(control.AutomationId)
                keyControl[automationId2key[control.AutomationId]]= control
        return keyControl

    def calculate(self, expression, keyControl):
        expression =''.join(expression.split())
        if not expression.endswith('='):
            expression +='='
            for char in expression:
                keyControl[char].Click(waitTime=0)
        self.calcWindow.SendKeys('{Ctrl}c', waitTime=0.1)
        return auto.GetClipboardText()

    def calc_demo(self):
        """计算器示例
        :return : 
        """        
        self.gotoScientific() # 选择科学计算器        
        keyControl = self.getKeyControl() # 获取按键控件
        result     = self.calculate('(1 + 2 - 3) * 4 / 5.6 - 7', keyControl)
        print('(1 + 2 - 3) * 4 / 5.6 - 7 =', result)
        self.calcWindow.CaptureToImage('calc.png', x=7, y=0, width=-14, height=-7) # 截图
        self.calcWindow.GetWindowPattern().Close() # 关闭计算机

if __name__ == "__main__":
    ui = uiautoCalc()
    ui.calc_demo()

脚本执行动图:

python uiautomation,自动化测试,自动化,python,uiautomation,windows gui 自动化

参考文档

  1. https://github.com/pywinauto/pywinauto

  2. https://cloud.tencent.com/developer/article/2213048

  3. https://github.com/yinkaisheng/Python-UIAutomation-for-Windows

  4. Python UIAutomation文档:https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/master/readme_cn.md

  5. https://www.cnblogs.com/Yinkaisheng/p/3444132.html

  6. GitHub - jacexh/pyautoit: Python binding for AutoItX3.dll

  7. GitHub - mhammond/pywin32: Python for Windows (pywin32) Extensions

  8. Accessibility tools - Inspect - Win32 apps | Microsoft Learn

  9. Accessibility Insights文章来源地址https://www.toymoban.com/news/detail-648324.html

--THE END--

到了这里,关于Windows GUI自动化控制工具之python uiAutomation的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • GUI自动化测试工具Sikulix的安装和使用

    GUI自动化测试工具Sikulix的安装和使用

    从程序内部控制对小白来说太难了,所以使用一下自动化测试的工具直接控制按钮达到我的目的 官网:http://www.sikulix.com/ 下载对应系统的.jar 需要使用java,没有的话安装一下 然后在sikulix的下载目录下执行 安装成功后就会弹出软件的窗口 上图左边是写程序的地方,右边是日

    2023年04月26日
    浏览(44)
  • Python之GUI自动化---selenium基础

    Python之GUI自动化---selenium基础

    1.GUI自动化也就是模拟人的操作来完成基础的功能测试。 2.GUI自动化测试中,需要明白测试脚本和数据的解耦。即实现数据驱动的测试,让操作相同但是数据不同的测试通过一套脚本来实现。 3.在写脚本中要注意“页面对象模型” 的核心理念:以页面为单位来封装页面上的控

    2024年02月05日
    浏览(14)
  • 一款GUI跨平台自动化测试工具分享——Squish,支持Qt框架

    Squish GUI 测试自动化工具使跨平台测试应用程序变得容易,它对Qt的支持非常好。 点击获取Qt组件下载 在发布应用程序之前测试用户界面比以往任何时候都更加重要,当今用户需要从移动、桌面、Web和嵌入式应用程序中获得无缝的跨平台体验。由于应用程序经常在工厂、汽车

    2023年04月12日
    浏览(49)
  • Python GUI自动化神器pyautogui,精准识别图片并自动点赞(32)

    Python GUI自动化神器pyautogui,精准识别图片并自动点赞(32)

    小朋友们好,大朋友们好! 我是猫妹,一名爱上Python编程的小学生。 欢迎和猫妹一起,趣味学Python。 今日主题 你听过GUI自动化吗? GUI自动化就是用软件模拟鼠标和键盘的操作。 提到Python GUI自动化,不得不提pyautogui,它使用简单功能强大。 没有安装pyautogui库的话,先用p

    2023年04月23日
    浏览(12)
  • windows桌面应用程序UI自动化工具

    WinApp(Windows APP)是运行在Windows操作系统上的应用程序,通常会提供一个可视的界面,用于和用户交互。 例如运行在Windows系统上的Microsoft Office、PyCharm、Visual Studio Code、Chrome,都属于WinApp。常见的WinApp,其扩展名基本都是*.exe,运行后也都会有一个漂亮、易用的UI界面,下面

    2024年02月11日
    浏览(12)
  • Python 自动化指南(繁琐工作自动化)第二版:二、流程控制

    Python 自动化指南(繁琐工作自动化)第二版:二、流程控制

    原文:https://automatetheboringstuff.com/2e/chapter2/ 所以,你知道单个指令的基本原理,程序就是一系列指令。但是编程的真正优势不仅仅是像周末跑腿一样一个接一个地运行指令。根据表达式的求值方式,程序可以决定跳过指令,重复指令,或者从几条指令中选择一条来运行。事实

    2023年04月08日
    浏览(44)
  • python自动化测试- 自动化框架及工具

    python自动化测试- 自动化框架及工具

    手续的关于测试的方法论,都是建立在之前的文章里面提到的观点: 功能测试不建议做自动化 接口测试性价比最高 接口测试可以做自动化 后面所谈到的  测试自动化  也将围绕着  接口自动化  来介绍。 本系列选择的测试语言是 python 脚本语言。由于其官方文档已经对原理

    2024年02月22日
    浏览(15)
  • Appium: Windows系统桌面应用自动化测试(四) 【辅助工具】

    Appium: Windows系统桌面应用自动化测试(四) 【辅助工具】

    @[TOC](Appium: Windows系统桌面应用自动化测试(四) 辅助工具) 文件批量上传和文件单个上传原理是相同的,单个上传直接传入文件路径即可,批量上传需要进入批量上传的文件所在目录,然后观察选中多个文件时【文件路径输入框】读取的批量文件写入规则,如图7-12所示,可以看

    2024年02月16日
    浏览(16)
  • 如何使用Python自动化测试工具Selenium进行网页自动化?

    如何使用Python自动化测试工具Selenium进行网页自动化?

    Selenium 是一个流行的Web自动化测试框架, 它支持多种编程语言和浏览器,并提供了丰富的API和工具来模拟用户在浏览器中的行为 。 Selenium可以通过代码驱动浏览器自动化测试流程,包括页面导航、元素查找、数据填充、点击操作等。 与PyAutoGUI和AutoIt相比, Selenium更适合于处

    2023年04月09日
    浏览(57)
  • python控制UI实现桌面微信自动化

    python控制UI实现桌面微信自动化

    Hello,我是新星博主:小恒不会java 背景 使用  wxpy   或者   itchat   这种第三方库通过Python控制自己的微信号,实现很多自动化操作,用的是微信网页版接口,不过随着微信的发展(信息安全等方面愈加重要,这种不符合官方期望出现的东西,很容易就破产。也由于itchat在

    2024年04月27日
    浏览(17)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包