[Windows automation] Realize win automation based on pywinauto module


foreword

In many cases, we need to repeatedly operate programs on Windows. If the manual method is used, this goal can indeed be achieved, but if it needs to be operated day and night, it is obvious that the manual method is a bit powerless, after all, people are not machines. We can use python to achieve this function, and python provides a large number of powerful libraries for us to use. pywinauto can help us realize windows automation. Of course, there are many modules that can assist in windows automation testing, such as time, datetime, logging, configparser, pyautogui, etc.
This article mainly introduces the use of pywinauto to realize windows automation. Use the pip install pywinauto command to download, and the download is complete with "successfully installed".


1. Steps to use

1. Import library

The code is as follows (example):

from pywinauto.application import Application

2. Open the specified program

Here we take opening the xshell application as an example to realize simple automation. First, use the small software inspect to determine the type of software, and it can also be used for element positioning. Generally speaking, the commonly used types are in the 'uia' format. If the window structure cannot be obtained using inspect, then the software is likely to be win32, and then it needs to be changed to 'win32', the code example is as follows:

app = Application(backend='uia').start('exe的路径')

Normally, using this code will start the application. It should be noted that during the automated testing process, it is necessary to keep the computer screen in an unlocked state, and at the same time, do not interrupt the automated operation process. Here is a simple example to automatically open the XMind application. The code example is as follows:

app = Application(backend='uia').start(r"C:\Program Files\XMind\XMind.exe")

At this point, you can see that the Xmind application has been successfully opened, and then use the Inspect application, you can see that the XMind window title is "XMinf", and we can use the class name to locate the window.

3. Control element positioning, window operation, control operation


After locating the window, you can use the print_control_identifiers() method to print out all the control information of the window. In the method, you can add the parameter depth as the printing depth. If you don’t add it, it will print all by default. In the method, you can also add the filename parameter to specify the file name. This is mainly to output the window control information to the text file. If you do not add this parameter, it will be printed to the console by default.

dlg = app["XMind"]
dlg.print_control_identifiers()

After executing this code, the console outputs all control information, as follows:

|    | Static - 'XMind'    (L508, T199

Guess you like

Origin blog.csdn.net/liaotianyin/article/details/130759310