1- What does uia in pywinauto mean?
exist
pywinauto
In the library,uia
Refers toUI Automation, This is a technical framework provided by the Windows operating system to implement automated testing of the user interface (UI) and access to auxiliary functions. UI Automation is a core technology introduced by Microsoft from Windows Vista, aiming to provide a consistent programming interface for all UI elements, regardless of the technology (such as Win32, WPF, UWP, etc.).exist
pywinauto
in, by specifyingbackend="uia"
, users can choose to use UI Automation as the underlying engine to interact with the UI elements of the application. This provides broader support for automated testing, especially when dealing with modern Windows applications, especially those built using WPF and UWP technologies. Compared with traditional UI Automation backendwin32
The backend provides richer and more advanced element attributes, control patterns and event support, making automated scripts more flexible and powerful.Using the UI Automation backend, developers can more easily locate and manipulate UI elements, such as obtaining the attributes of elements, simulating mouse and keyboard operations, listening to UI events, etc., which is especially useful for creating complex automated test scenarios.
2-Detailed introduction to main_window.child_window() method and parameters in pywinauto
existpywinauto
middle,child_window()
The method is used to locate a specific child window or control in the parent window. This is essential for accurately finding and manipulating specific UI elements in automated testing. The following is the rightchild_window()
Detailed description of methods and parameters:
Basic usage
child_window()
The method belongs to the window object and is used to search for the first child window that meets the specified criteria among all child windows in the current window. The basic syntax is as follows:
Python
1parent_window.child_window(arguments)
in,parent_window
It is the window object you have already obtained.arguments
is a series of keyword parameters used to filter child windows.
Detailed explanation of parameters
child_window()
Methods accept multiple keyword parameters to accurately locate subwindows, common parameters include but are not limited to:
- title: String, title or text of the control.
- class_name: String, class name of the control.
- control_type: String, type of the control (only valid under UIA backend).
- auto_id: string, the automation ID of the control (AutomationId).
- name: String, name attribute of the control, may be different from the title or automation ID.
-
backend: String, specify the backend type, such as
'win32'
or'uia'
, automatically selected by default. - process: integer, specifying the process ID of the target window.
- enabled: Boolean value, whether to look for only enabled controls.
- visible: Boolean value, whether to look for only visible controls.
- top_level_only: Boolean value, whether it is only found in the top-level window.
- found_index: Integer, when multiple matches are found, you can select matches for a specific index.
- control_id: integer, control ID (control ID in Windows API).
-
handle: integer or
ctypes.c_void_p
, directly specify the handle of the control. - regex_title: A regular expression object or string that matches the title regular expression.
- regex_class_name: Same as above, but used to match class names.
-
best_match: string, used for
best_match()
Logical, try to match the closest control.
Example
Suppose you want to find a menu item named "File" in the main window of the Notepad application, you can do this:
Python
from pywinauto import Application app = Application(backend="uia").start("") main_window = (title="Unt title - Notepad") # Use class_name and title to locate subwindowsmenu_item = main_window.child_window(class_name="MenuItem", title="document")
Things to note
-
Parameter combination: Usually, for exact matches, you need to use it in combination with multiple parameters. For example, use it at the same time
class_name
andtitle
The target control can be positioned more accurately. - Performance considerations: If the condition is set too broad, it may cause slow searches or find wrong controls. Try to use specific attributes to narrow the search scope.
-
Exception handling: If the matching child window cannot be found,
child_window()
An exception will be thrown. This situation can be handled properly using the try-except structure.
By using flexiblychild_window()
Methods and their parameters, you can efficiently locate and manipulate various elements in UI automation.
3-Child_window() / children() / descendants() method introduction
If you want to get all direct child windows under the parent window (rather than just a single child window), you can usechildren()
method, it returns a list of all direct child elements. This element positioning method requires the window type to be: WindowSpecification
For example:
Python
all_direct_children = parent_window.children()
If you need to recursively get all descendant windows (child windows and child windows of child windows, etc.), you can usedescendants()
Method, the way this element is positioned, the window type is required to be: UiaWrapper:
Python
all_descendants = parent_window.descendants()
In summary,parent_window.child_window()
It is used to locate a single child window that meets a specific condition, rather than fetching all child content. To get all sub-contents, usechildren()
ordescendants()
。
4- When pywinauto opens the program, the program starts slowly, or clicks button pop-ups slowly, or opens a new window and renders it slowly, how to add a reasonable waiting time
In usepywinauto
When performing automated operations, it is very important to reasonably add waiting time, especially when the program starts slowly, the pop-up window is delayed after the button is clicked, or the new window rendering speed is slow. This ensures that the script waits for the relevant UI elements to be ready before continuing with the next operation. Here are a few ways to add waiting time:
1. Explicit waiting (recommended)
usewait
The method is the most flexible and recommended way of waiting, which allows you to specify the waiting conditions and timeout time.
Wait for the window to be visible:
Python
(title="Window Title").wait("visible", timeout=10)
Wait for the control to be available:
Python
.child_window(title="Button Title", control_type="Button").wait("enabled", timeout=20)
2. Static waiting ()
Although not as flexible as explicit waiting, it can be used in some simple scenariosTo simply pause script execution.
Python
import (5) # wait5Second
3. Dynamic waiting
For some operations that are uncertain when to complete, dynamic wait can be achieved in the loop in combination with check conditions and short pauses.
Python
import time timeout = 30 # Total timeoutinterval = 1 # Check intervalsstart_time = () while () - start_time < timeout: if (title="Window Title").exists(): break (interval) else: raise TimeoutError("The window did not appear within the specified time")
4. Use backend features
Some backends (e.g.uia
) provides more advanced waiting logic, such as can be exploited when starting an applicationApplication().start(..., timeout=...)
To specify the startup timeout.
5-pywinauto How to locate a specific window when the app opens has multiple different windows
existpywinauto
In, if an application opens multiple different windows and wants to locate a specific window, you can accurately filter according to the characteristics of the window. Here are some commonly used filtering methods:
1. According to the title of the window (Title)
Window titles are usually the most intuitive attributes that distinguish different windows. You can locate windows using exact text or regular expressions of window titles.
Python
specific_window = (title="Exact title of window") # Or use regular expressions to fuzzy matchesspecific_window = (title_re="Part of the window title.*")
2. Combined with Class Name
If the titles of multiple windows are similar but the class names are different, you can filter them together with the class names.
Python
specific_window = (title="Window Title", class_name="Window Class Name")
3. Control Type and Automation ID
When using the UIA backend, if there are specific types of controls in the window or the control has a unique Automation ID, it can also be used as a positioning basis.
Python
# Assume that there is a specific control type or ID in the windowspecific_window = (control_type="Window", automation_)
4. Use child windows or descendant windows
If the window you need to locate is a child window or descendant of another window, you can first locate the parent window and then passchild_window()
ordescendants()
Method to find the target window.
Python
parent_window = (title="Parent window title") specific_child_window = parent_window.child_window(title="Sub-Window Title") # Or iterate through all descendant windows to find a matching onespecific_descendant_window = parent_window.descendants(title="Descendant Window Title")[0] # Note that this returns a list
5. Pass the Handle
If you already know the handle of the window, you can connect to the window directly through the handle.
Python
from import win32functions handle = (None, None, "Window Class Name", "Window Title") specific_window = (handle=handle)
Things to note
- In use
wait
Methods ensure that the window is loaded and visible, especially when positioning a dynamic pop-up window, which can avoid errors caused by the window not being ready. - When multiple windows match the same filter criteria, consider using more specific filter criteria or combining multiple attributes to locate.
- If the window is created in a different process, you may need to use it
()
Method to connect to that window separately.
6-Usage of element_info and BaseWrapper in pywinauto
existpywinauto
middle,element_info
andBaseWrapper
are two core concepts that play an important role in automated testing and interface operation.
element_info (pywinauto.element_info.ElementInfo
)
element_info
It is an underlying, element-oriented abstract class that provides access and description of UI element attributes, but does not directly support operations. It is a lightweight package that stores and passes information about UI elements such as class names, titles, locations, etc. without involving actual UI operations.element_info
It is the basis of all control information, regardless of which backend the control passes (e.g.win32
, uia
) to identify.
When you usepywinauto
Methods (such aschild_window()
) When locating an element, it is actually creating or searching for an element.element_info
Object.element_info
Objects can be used to create more advanced wrapper objects, such asBaseWrapper
。
BaseWrapper (pywinauto.base_wrapper.BaseWrapper
)
BaseWrapper
It is based onelement_info
A higher-level packaging not only contains the information of the element, but also provides methods to operate on the element, such as clicking, sending text, obtaining attributes, etc. When you need to interact with UI elements, such as clicking a button or filling in a text box, you should useBaseWrapper
Object.
BaseWrapper
yeselement_info
Direct extension of , it converts underlying element information into actionable objects. This means that you canBaseWrapper
Direct execution as.click()
, .set_text()
, .texts()
, .exists()
and other operations make automated script writing more intuitive and convenient.
Example of usage
Suppose you want to operate a button, you can follow the following steps:
Python
from pywinauto import Application app = Application().start("your_app.exe") main_win = (title="Main Window Title") # Use the child_window() method to find a button and get a BaseWrapper instancebutton = main_win.child_window(title="Click Me", control_type="Button") # Then, you can directly call the BaseWrapper method to operate this button()
In this process, although not directly usedelement_info
, but in factchild_window()
Internal processing fromelement_info
arriveBaseWrapper
The conversion allows you to interact directly with UI elements.
7-What other methods are there in pywinauto's BaseWrapper class, detailed description
According to the searched content, the following is summarized as follows
pywinauto
ofBaseWrapper
Classes provide many ways to manipulate and query UI elements. These methods cover access to complex UI interactions from basic properties, belowBaseWrapper
An overview and brief description of some commonly used methods in the class:
Common properties and methods.window_text()
: Get the text content of the control.
-
.texts()
: Returns a list of all text contents of the control, suitable for controls containing multiple lines of text. -
.class_name()
: Returns the class name of the control. -
.control_type()
: When using the UIA backend, return the type of the control. -
.enabled()
: Check whether the control is enabled. -
.visible()
: Check whether the control is visible. -
.rectangle()
: Gets the rectangular area of the control, including coordinates and size. -
.set_focus()
: Set focus on the control. -
.click_input()
: Simulate mouse click control. -
.double_click_input()
: Double-click the control. -
.right_click_input()
: Right-click on the control. -
.drag_drop(target)
: Drag the control to the specified target. -
.type_keys(keys, with_spaces=True, set_foreground=True)
: Send keyboard input to the control. -
.set_text(text)
: Set the contents of the text control. -
.texts()
: Gets all text content of the control, suitable for controls that may have multiple lines of text.
Control positioning and operation extensions
-
.child_window(**kwargs)
: Find and return matching conditions in the child control of the current controlBaseWrapper
Object. -
.descendants(**kwargs)
: Returns a list of all descendants of the current control that meets the given filter criteria. -
.parent()
: Returns the current control's direct parent controlBaseWrapper
Object. -
.top_parent()
: Returns the top-level parent control of the current controlBaseWrapper
Object. Attribute acquisition and setting -
.get_properties()
: Get all attribute information of the control. -
.set_property(name, value)
: Sets the property value of the control. Image operation.capture_as_image()
: Snaps the image of the control and returns a PIL image object. other.wait('exists', timeout=timedelta(seconds=5))
: Wait until the control exists until timeout. -
.wait('visible', timeout=timedelta(seconds=5))
: Wait for the control to become visible. -
.wait_not('visible', timeout=timedelta(seconds=5))
: Waiting for the control to be no longer visible.
Only some of the methods listed above, in factBaseWrapper
The class contains more features, covering most of the requirements for automated testing and UI operations. For specific usage methods and parameters, please refer topywinauto
official documentation or view source code comments directly for the most comprehensive and latest information.
-
Try explicit type conversion: If applicable, you can try to convert the found element to a specific control type and then call
.click_input()
method.
Python
from .win32_controls import ButtonWrapper button = ButtonWrapper(element) button.click_input()
If none of the above methods can solve the problem, please refer topywinauto
Official documentation or visit its GitHub page to see if there are any related issue reports or update logs. At the same time, make sure your Python environment is up to date and consider upgradingpywinauto
To the latest stable version.
8-What control type can pywinauto be converted to Wrapper
pywinauto
A series of Wrapper classes for different control types are provided. These classes encapsulate operation methods for specific types of controls, making automated operations more intuitive and convenient. The following are some commonly used control types and their corresponding Wrapper classes:
Button - ButtonWrapper
Used to operate buttons, support clicks and other operations.
Edit - EditWrapper
Used for editing boxes, supporting text settings, acquisition and other operations.
ComboBox - ComboBoxWrapper
Used for combo boxes (drop-down list), supports selection, get option list, etc.
ListBox - ListBoxWrapper
Used in list boxes, support selection, obtaining item list, etc.
CheckBox - CheckBoxWrapper
Used for check boxes, support checking, unchecking and status checking.
RadioButton - RadioButtonWrapper
Used for radio buttons, support selection and status checking.
Menu - MenuWrapper
Used for menu items, supports expanding menus, selecting menu items, etc.
TreeView - TreeViewWrapper
Used for tree view controls, supporting node expansion, selection, etc.
TabItem - TabWrapper
Used for a single tab in a tab control.
Dialog - DialogWrapper
Special treatment of dialog windows, although they are also windows, may contain dialog-specific operation methods.
Window - WindowWrapper
Common window class, almost all windows can be operated with this class, but it is more convenient to use specific Wrappers for specific control types.
Please note that directlyelement_info
Convert to a specific Wrapper class (such as fromelement_info
arriveButtonWrapper
) is not always directly supported, and usually you don't need to do such a conversion manually. When you pass the correct filter criteriachild_window()
When you wait for the method,pywinauto
It will automatically provide you with the most suitable Wrapper instance. If more specific control operations are required, you can accessBaseWrapper
The attributes or methods of the instance are implemented, because most Wrapper classes are fromBaseWrapper
Inherited, it already contains the basic interactive methods.
In actual use, use it directlychild_window()
The method can locate and operate the control based on the properties of the control (such as title, class name, control type, etc.). In most cases, there is no need to care about the underlying Wrapper class conversion. If more advanced or specific features are required, please checkpywinauto
It is more helpful to understand how to use specific Wrapper classes.
9-pywinauto prints the obtained windows object, one is added with waiting, and the other is not added with waiting.
The obtained window object uses print(window), and the printed one is - 'New mail', Dialog, and the other is <object at 0x0000016B0DE556A0> What is the difference
In usepywinauto
When you observe the difference reflects the way window object is handled in two different states.
Waiting not used (get it directly)
Python
window = (title="New mail") print(window)
The output is similar to< object at 0x0000016B0DE556A0>
, which shows that you are getting aWindowSpecification
Object. This object is actually a window descriptor or specification that defines the conditions that the window you are looking for should meet (in this example, a window titled "New mail"). However, at this timepywinauto
This window has not been actually found and instantiated, which means that the printed information is a memory address, representing the instance of the window to be found.
Use wait to get
Python
window = (title="New mail").wait('visible') print(window)
or
Python
window = (title="New mail").wait('exists', timeout=10)
The output is - 'New mail', Dialog
, This means that you have successfully obtained an actual UI element object. It is no longer a simple search specification, but an operational object that actually exists in the window.yes
pywinauto
The class internally used to wrap the UIA (UI Automation) element, which means that the window is not only found, but is also ready for further interaction, such as clicking, entering text, etc.
Summary of the difference
- Unused waiting: What you get is a window's lookup descriptor, which defines what to look for, but does not mean that the window has been found or instantiated.
- Use waiting: What you get is an actual UI element object, which represents the window that has been found and can be used directly to perform various operations.
In practical applications, use wait (e.g..wait('visible')
or.wait('exists')
) is generally more recommended because it ensures that operations are not performed when the window is not ready, improving the stability and reliability of the script.
10- After my pywinauto program, after (), I also need to execute the app after () to be used normally. Otherwise, the windows obtained by this app are unavailable, why?
existpywinauto
In theory, once you use()
Method starts an application, which should automatically connect to this newly launched application instance, and you can directly return itapp
The instance searches and operates windows and controls without calling them again()
。
If you encounter it, you must execute it first()
Only then can it be used normallyapp
The window or control obtained, which may be caused by several reasons:
-
Startup time issue: It may take some time for the application to fully initialize its window and UI elements. even if
start()
The method attempts to connect internally, but if the UI is not fully loaded, subsequent window or control searches may fail immediately. At this time, call manuallyconnect()
Give extra time buffering, which may just make the UI ready. -
Start or hide windows in the background: Some applications may not display the window immediately upon startup, or the window is minimized to the tray/background running, resulting in the window not being correctly identified on the first connection. Called later
connect()
The window may have become visible or interactive. -
Compatibility or bugs of UI automation framework: Although rare, different versions of
pywinauto
Or the target application's UI framework (such as WPF, UWP, etc.) may have compatibility issues, resulting in the automatic connection behavior not as expected. -
Multiple instance problems: If your application allows or accidentally launches multiple instances,
start()
It may be connected to a different instance, and the window you expect to operate is in another instance. Manually specify the connection conditions again to ensure that you connect to the correct window instance.
Solution suggestions:
-
Increase waiting after startup:exist
start()
After that, add appropriate waiting time (e.g.()
), giving the application enough time to initialize windows and UI elements. -
Precise connection:make sure
connect()
Use sufficient parameters (such as window title, class name, etc.) to accurately match the window you want to connect to, avoid connecting to wrong instances or windows. -
examine
pywinauto
Version: Make sure you use itpywinauto
The version is the latest for optimal compatibility and stability. -
Logging and debugging:use
pywinauto
Logging function or printing debugging information, check for any exceptions or warnings that may occur during startup and connection, and help locate the problem.
If the problem persists, consider checkingpywinauto
Official documentation or community that may be targeted at specific targets
Use or similar solutions.
My problem should actually be a compatibility issue. I increased the waiting time after starting(), which was invalid.
The () command must be used to re-get the app, and only the operations are valid.
app = Application(backend="uia").start(outlook_path, timeout=30) # Waiting is also a must(15) # Must be regenerated using connect()app = Application(backend="uia").connect(class_name="Olk Host") print("outlookFirst start,Openoutlooksuccess!, app=", app)
11-Is there a timeout parameter in the Application(backend="uia").start() parameter?
No.
Because in standardpywinauto
Documentation and common use, directstart()
The method call does not directly accept atimeout
Parameters are used to wait for the application to start.
Usually, if you want to control the waiting logic after the application starts or process timeout, you need to take some extra steps instead of directly passingstart()
Methodtimeout
Parameters (because this parameter does not exist in standard usage). Here are some suggestions:
-
Wait manually:exist
start()
After the call, you can use()
Or more complex logic to wait for an estimated reasonable time to ensure that the application has enough time to start and load. -
Dynamic waiting window:use
pywinauto
waiting mechanism, such astop_window()
orwait()
Method to dynamically wait until a window of the application becomes available or meets certain conditions. For example, if you know the title of the main window after the application starts, you can do this:
Python
app = Application(backend="uia").start("your_app_path") main_window = (title="Your Main Window Title").wait("visible", timeout=30)
here,timeout=30
It is the maximum time to wait for the window to become visible, in seconds.
Exception handling: When trying to access the application window or perform an operation, use the try-except structure to catch possible timeouts or failure exceptions, thereby achieving indirect timeout control.
Custom logic: Depending on the specific behavior of the application, you may need more customized logic to determine when the application has been successfully started and ready for automation, which may involve checking the status of a specific process, changes in window properties, etc.
To sum up, although directly()
Settings in the methodtimeout
Parameters are not standard usage, but through the above methods, you can effectively control and manage the waiting logic and timeout processing after the application is started.
12-Is there a timeout parameter in the Application(backend="uia").connect() parameter?
No.
butpywinauto
Flexible wait and timeout control mechanisms are provided to ensure that connection operations do not block indefinitely.
Automated waiting and timeout control
Although directlyconnect()
The method signature is not disclosedtimeout
Parameters, butpywinauto
ofwait
Series of methods and automations usually allow you to specify a timeout limit, such as when trying to connect to a window:
Python
app = Application(backend="uia") main_window = (title="Your App Title").wait("exists", timeout=30)
In this example,wait("exists", timeout=30)
It is to try to wait for the window to exist for up to 30 seconds. If the window becomes accessible within a specified time, it continues to execute; if it timed out, an exception will be thrown, allowing your script to react accordingly.
Custom waiting logic
For more complex scenarios, you may need to customize the waiting logic, such as checking whether the window not only exists but also meets other conditions (such as "visible", "enabled", etc.), and combining custom loops and timeout processing.
Summarize
althoughApplication(backend="uia").connect()
Direct calls do not come with a cleartimeout
parameter,pywinauto
Providedwait
The flexibility of methods and automation allows you to effectively control the time limits of connection and waiting for windows to appear, implementing logic similar to timeout processing. In this way, it is ensured that the automated scripts can both wait for the necessary windows to be ready and avoid unnecessary blockages.
13-Popular window operation
existpywinauto
When you need to connect and operate a new pop-up window in the application, you usually need to make sure that the new window has appeared, and then locate and operate it through the window's title or other properties. Here are the basic steps to deal with new pop-ups:
1. Wait for the pop-up window to appear
usepywinauto
The wait function ensures that the pop-up window has been opened. This can be done by looping to check if the window exists, or using a more advanced wait method.
Python
from pywinauto import Application from import wait_until_passes app = Application().connect(title="Title of main application") # Connect to the main application firstdef is_popup_opened(): try: (title="Pop-up Title") return True except Exception: return False # Wait for a pop-up window to appear, wait for up to 10 secondswait_until_passes(10, 1, is_popup_opened)
2. Position and operate pop-up windows
Once the pop-up window is confirmed to be open, it can be positioned and operated through its title or other properties.
Python
popup_window = (title="Pop-up Title") # For example, click a button on the pop-up windowbutton_on_popup = popup_window.child_window(title="Title or automation ID of the button", control_type="Button") button_on_popup.click()
3. Exception handling and retry mechanism
In actual operation, it may be necessary to add appropriate exception handling logic to prevent window title from changing or opening speed too slowly.
4. Close the pop-up window
If you need to close the pop-up window after the operation is completed, you can call the window's closing method:
Python
popup_window.close()
Notes:
- Make sure the window title is unique, or is accurate enough to avoid misoperating other windows.
- use
control_type
、class_name
Properties like this can help position controls more accurately. - If the pop-up is part of the same application, it usually does not need to be called again
Application().connect()
, just operate directly on the connected application instance. - Depending on the timing of the pop-up window and the specific behavior of the application, it may be necessary to fine-tune the waiting logic.
14-AttributeError: 'UIAWrapper' object has no attribute 'print_control_identifiers'
existpywinauto
If you encounterAttributeError: 'UIAWrapper' object has no attribute 'print_control_identifiers'
Error, which means you tried to use it on a UIA (UI Automation)-based controlprint_control_identifiers
Method, but this method does not actually exist directly inUIAWrapper
in object.
print_control_identifiers
Methods are mainly used for classic Windows application automation (win32 applications), which is inWin32Window
Available in the object. However, for applications based on UI Automation (UIA), such as modern UWP applications or desktop applications built with the UIA framework, use it directlyprint_control_identifiers
An error will be reported.
For UIAWrapper objects, you can use.legacy_properties()
Methods to get some information about the control, but this is usually not as good asprint_control_identifiers
That's so detailed.
Solution:
- Check the application type: Confirm whether your application is a modern UIA application or a traditional win32 application. If it is a UIA application, continue reading below.
-
Use UIA properties: For UIAWrapper objects, you can use
.properties
Properties to view the properties of the control. For example:
Python
1control = (title="Your Window Title").child_window(auto_) 2print()
This prints out the control's attribute dictionary, which contains information such as control type, name, location, etc.
Custom printing functions: If needed, similarprint_control_identifiers
You may need to write a function to traverse the detailed output of.properties
Or use other UIA methods to get more detailed control information.
Downgrade to win32: In some cases, if the application supports both UIA and win32, you can try downgrading to win32 mode to useprint_control_identifiers
. But it depends on the specific implementation and support of the application, and not all UIA applications can do this.
Remember, UI Automation and classic Windows application automation inpywinauto
There are some differences in this, so when dealing with different types of windows and controls, adjust your approach accordingly.
15-AttributeError: 'UIAWrapper' object has no attribute 'child_window'
UIAWrapper window type, you need to locate elements using the following method: ele = (title="Remove")[0]
When you are usingpywinauto
meetAttributeError: 'UIAWrapper' object has no attribute 'child_window'
When errors, this means you try to use a UIA (UI Automation)-based control (UIAWrapper
Called on the object)child_window
Method, but this method is not available in UIAWrapper object.
The UIAWrapper object mainly corresponds to applications that use UI Automation technology, which is different from the API used by traditional Win32 applications. On UIAWrapper, the method to directly find a child window or control is notchild_window
, instead use properties and methods that are more in line with UIA query methods.
Solution:
- use
.descendants
Method: For UIAWrapper object, you can use.descendants
Method to find all descendant controls, and then find the target control through conditional filtering.
Python
controls = (control_type="ControlType") # replace"ControlType"For the actual control type,like"Button", "Edit",
Direct attribute access: If certain attributes are known (such asname
, control_type
etc.), you can directly filter through attributes.
Python
target_control = window.child_window(auto_)
Note: The abovechild_window
The method is for classic win32 applications. For UIA, you should use methods that are more consistent with their query mechanism, such as.descendants
Or direct attribute filtering.
Construct query conditions: Use more complex query conditions to pinpoint controls, for example.filter()
method.
Python
1from .uia_controls import UIAWrapper 2control = UIAWrapper(handle=Your window handle).filter(control_type="ControlType")[0] # replace"ControlType"and conditions
Make sure to understand whether your application is based on UI Automation or traditional Win32, and then select the corresponding API and method to manipulate and find controls. For UIA applications,.descendants
and attribute filtering is usually the most direct and effective way.
16-pywinauto, the window has been found, but using the window method print_control_identifiers() method will prompt that multiple elements are matched? There are 5 elements that match the criteria {'backend': 'uia', 'process': 22188}
When you have successfully located a window, but try to usewindow.print_control_identifiers()
A prompt was encountered when a method matched multiple elements, which usually means that you callprint_control_identifiers()
The object is actually a collection of windows or a window specification based on certain broad conditions (WindowSpecification
), not a specific window instance.
To solve this problem, make sure you are callingprint_control_identifiers()
Previously, a unique window has been specified accurately. Here are a few steps to help you:
- Recheck the code for positioning windows: Confirm that you have indeed been positioned to a single window with sufficiently accurate conditions. For example, use the window's title, class name, process ID and other attributes to accurately filter.
-
Use more specific selectors: If possible, add filtering conditions, such as using regular expressions to match window titles (
title_re
) or use the window's automation ID directly (auto_id
)。 - Make sure the call chain is correct: If a window is reached through a series of operations, confirm that each step correctly returns the expected window object. Sometimes, the wrong order of calls can result in a collection of windows rather than a single window being returned.
-
Check if fuzzy matching is used: Avoid using too broad conditions that may match multiple windows, such as using only
backend
andprocess
As a filter. - Externally get window instance: After determining the window, you can try to explicitly obtain the specific window instance through indexing or other methods. For example, if you know that the target window is the first in a matching condition, you can try:
Python
specific_window = windows[0] # Assume 'windows' is a list of multiple matching windowsspecific_window.print_control_identifiers()
- use
top_level_only=False
: If the target window is not a top-level window, try setting ittop_level_only=False
Go to search for windows at all levels and filter them further. -
Debugging and Analysis: If none of the above methods can solve the problem, you can use it first
print_control_identifiers()
ofdepth=-1
Parameters to print information about all windows, help you identify which windows do not match your expectations, and adjust the selection criteria accordingly.
Make sure each step is as specific and precise as possible to avoid matching multiple windows.
17-pywinauto, use Desktop(backend="uia") to get window
Note1: Desktop(backend="uia").windows()/window(),Two methods,Only query all main windows,It does not support querying the main window.。 Note2: useDesktop(backend="uia").windows()/window(),If the condition cannot be located to the window。 Desktop(backend="uia").windows()method,The result returns to an empty list。 as follows: wins = Desktop(backend="uia").windows(title="Work or school account", class_name="") print(wins) result:[] Desktop(backend="uia").window()method,result返回WindowSpecificationObject。 as follows: win = Desktop(backend="uia").window(title="Work or school account", class_name="") print(win) result:< object at 0x000001524BE87790>,不能use返回的window()The return value is judged。 Note3: If the window type is:WindowSpecification,useparent_window.child_window() Query window elements。 If the window type is:UIAWrapper,useparent_window.parent_window.descendants() Query window elements。
18-pywinauto, through the element's () method, using pyautogui, move the mouse to the element's position, and implement it.
The specific writing method is as follows:
# Suppose you want to operate on an element in the window, first find the elementelement = main_window.child_window(title="Your Element Title", control_type="ControlTypeHere") # Please replace with the actual title and control type# Get the rectangle information of the elementelement_rectangle = () # Use pyautogui to move the mouse to this positionx, y = element_rectangle.left + (element_rectangle.width() // 2), element_rectangle.top + (element_rectangle.height() // 2) (x, y) # Move to the center of the element,You can also move directly to the upper left corner,Just remove the addition part
Note: element_rectangle.width and element_rectangle.height return types are method; the calculation of position coordinates should use element_rectangle.width() and element_rectangle.height() forms.
Otherwise, an error is reported: TypeError: unsupported operand type(s) for //: 'method' and 'int' (these two types are not supported to use // syntax calculation)
19-During the encoding process, pay attention to the circular reference problem
E ImportError: cannot import name 'assertTrue' from partially initialized module 'assertTool' (most likely due to a circular import) --It is likely to be a loop import
Problem: "File a" imports the method in "File b"; "File b" also imports the method in "File a", resulting in loop import problems.
20-pywinauot, when positioning the uiaWrapper element, adding waiting sometimes does not solve the problem. But after the window is maximized, the elements can be found.
Possible reasons:Changes in window layout
The layout of the internal elements of the application window may change slightly before and after it is maximized. This layout change may affect the accessibility of the element or cause changes in the element's properties (such as coordinate positions). The maximum window may cause the element to appear stably in the expected position or state, thus becoming possiblepywinauto
Identify.
21-Pywinauto + pytest When executing test cases, an error prompted: Windows fatal exception: code 0x8001010d. However, if the contents of this use case are put into a file and executed without passing pytest, there will be no error message. How should I solve it
Error code0x8001010d
It is usually related to COM (Component Object Model) errors, especially "RPC server is not available" or "Errors appearing in interface calls". In usepywinauto
There are several possible reasons for this problem when conducting GUI automation testing, especially in combinationpytest
When used, it may be related to the initialization of the test environment, resource release, concurrent execution of tests, etc. Here are some possible solutions:
-
Ensure singleton mode: Ensure that the use of application instances is singleton throughout the test suite, avoiding multiple test cases operating the same application instance at the same time, which may lead to resource conflicts. Can be
Used in
fixture
to manage the life cycle of an application instance. -
Resource Cleanup: Make sure that after each test case is finished, all open windows and resources are properly closed and cleaned. use
try...finally
Block orof
yield
Statement to ensure that the cleanup operation can be performed even if the test fails. -
Concurrent execution issues: If your test suite is configured to execute in parallel (pytest may not be by default, but by
-n NUM
Parameters can be set), then parallel execution may need to be disabled, as some GUI operations or COM objects may not support multithreading or concurrent access. Can be added when running pytest-n 1
Parameters to disable parallel execution. -
COM object life cycle management: Ensure that all COM objects are properly released after use. exist
pywinauto
This is usually handled automatically, but if custom COM calls are involved, make sure to follow the correct release process. - Add exception handling: Adding catching and handling logic for specific exceptions in the test code, especially COM-related exceptions, can help diagnose the problem. You can try to capture and print detailed error information for further analysis.
- Check environmental differences: Confirm whether the direct running file is consistent with the environment (such as environment variables, permissions, etc.) when running through pytest. Sometimes, environmental differences can lead to such problems.
If the above suggestions do not solve the problem, a more detailed log may be required to locate the problem. Consideringpytest
Increase log level at runtime (by-vvv
Parameters or configuration logging modules) and see if there are other related warnings or error messages output, which helps to more accurately locate the problem.