Python之uiautomation模块-获取CMD窗口中所打印的文字信息 当我们想以自动化的方式操作软件,以提高办公或测试效率时,有许多成熟的工具,比如针对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库。

接下来,调用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