当我们想以自动化的方式操作软件,以提高办公或测试效率时,有许多成熟的工具,比如针对Web端应用的Selenium、针对移动端应用的Appium。那么,PC端(Windows)桌面应用,又改如何处理呢?

微软给我们提供了解决方案,即UI Automation ,它能方便我们自动化操作PC端桌面应用程序,微软是这样介绍它的:

Microsoft UI Automation is an accessibility framework that enables Windows applications to provide and consume programmatic information about user interfaces (UIs). It provides programmatic access to most UI elements on the desktop. It enables assistive technology products, such as screen readers, to provide information about the UI to end users and to manipulate the UI by means other than standard input. UI Automation also allows automated test scripts to interact with the UI.

美中不足的是,该工具支持C/C++调用。对于以Python为常用语言的我来说,则需要想想办法。恰好,已经有Python库为我们封装了微软UI Automation的API,即uiautomation库。为了初步介绍如何使用该库,我们将解决一个实际问题:如何获取CMD窗口中所打印的文字信息?

首先,安装uiautomation库。

pip install uiautomation

接下来,调用uiautomation库提供的方法去定位CMD窗口中的文字信息。这里有一个问题,我们如何去定位CMD窗口?微软提供了UI Spy供开发者使用,界面如下所示,通过它能够快速获取窗口或控件的属性信息,其中就包括标识信息。

在UI Spy中找到CMD窗口下的文档控件,可以看到右边属性栏显示了Text信息,该Text信息就是我们要的目标文字。只要通过uiautomation库获取该Text信息即可。

uiautomation库的具体用法可以查看该库作者写的教程,下面是我给出的示例,用于获取CMD窗口中打印的文字信息。

import uiautomation

cmd_window = uiautomation.WindowControl(searchDepth=1, Name='管理员: 命令提示符', AutomationId='Console Window')
cmd_text = cmd_window.DocumentControl(searchDepth=1).GetTextPattern().DocumentRange.GetText()
print(cmd_text)

运行结果:

D:\>ping baidu.com

正在 Ping baidu.com [220.181.38.251] 具有 32 字节的数据:
来自 220.181.38.251 的回复: 字节=32 时间=49ms TTL=47
来自 220.181.38.251 的回复: 字节=32 时间=52ms TTL=47
来自 220.181.38.251 的回复: 字节=32 时间=49ms TTL=47
来自 220.181.38.251 的回复: 字节=32 时间=52ms TTL=47 220.181.38.251 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 49ms,最长 = 52ms,平均 = 50ms D:\>

参考资料

  • https://docs.microsoft.com/en-us/windows/win32/winauto/entry-uiauto-win32
  • https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/master/readme_cn.md

最新文章

  1. 用Asp.net写自己的服务框架
  2. CDC 2013 北京站手记
  3. hdu 5877/ 2016 ACM/ICPC Dalian Online 1010 Weak Pair
  4. 简单介绍Android应用特色及详解四大组件
  5. ABP的事件总线和领域事件(EventBus & Domain Events)
  6. python中那些双下划线开头得函数和变量--转载
  7. JavaScript语言基础知识10
  8. OpenCV备忘
  9. 关于ajax跨域问题
  10. zTree实现地市县三级级联Service接口实现
  11. angular-cli.json常见配置
  12. ionic3使用@angular/http 访问nodejs(koa2框架)服务不能返回数据
  13. Ribbon - WeightedResponseTimeRule原理
  14. Generative Adversarial Nets[pix2pix]
  15. dasd
  16. Linux包系列的知识(附:Ubuntu16.04升级到18.04的案例)
  17. [VC6,VC9] [ts,nts,deb] [rpm,msi] 你需要下载什么格式的文件
  18. .net开源项目整理
  19. WorldWind源码剖析系列:视景体类Frustum
  20. Python-统计svn变更代码行数

热门文章

  1. DNS的原理和解析过程
  2. pointnet.pytorch代码解析
  3. Mariadb常用管理操作
  4. charles抓取https设置
  5. 攻防世界pwn高手区——pwn1
  6. 一个遵循CleanArchitecture原则的Asp.net core轻量级开源项目
  7. Git-03-工作区和暂存区
  8. AI中各种浮点精度概念集合:fp16,fp32,bf16,tf32,fp24,pxr24,ef32
  9. NOIP 模拟 $38\; \rm a$
  10. 10、二进制安装K8s之部署CoreDNS 和Dashboard