Skip to content

Advanced

XPath, combined conditions, tree walking, caching, retries, fluent assertions and input timing. Each recipe shows Python next to the original FlaUI C#.

Every Python snippet on this page runs

The Python tabs are included from examples/pytest/test_advanced.py, which runs against the bundled WPF app:

uv run pytest examples/pytest/test_advanced.py -v

The snippets assume window, cf (automation.cf) and automation, as in the pytest example.

Element methods by type

Each page in the API Reference lists every method, including inherited ones. The highlights:

  • Button: invoke, click, right_click, double_click
  • CheckBox: toggle, toggle_state, is_checked
  • RadioButton: is_checked (get / set)
  • ComboBox / ComboBoxItem: select(value | index), items, selected_item, expand / collapse
  • TextBox: text (get / set), enter
  • ListBox / ListBoxItem: select(index | text), items, selected_item
  • Slider / Spinner: value (get / set), minimum, maximum, small_increment, ...
  • Tab / TabItem: select_tab_item, selected_tab_item, tab_items
  • Tree / TreeItem: items, expand, collapse, select, selected_tree_item
  • Grid / DataGridView: header, rows, cells, select
  • Window: title, close, modal_windows, title_bar, context_menu
  • Menu / MenuItem: items, invoke, expand

Finding elements

FlaUI has two main ways to find elements: the ConditionFactory (fast and specific) and XPath (flexible and structural).

Tree scope

Every search has a scope:

  • Children: direct children only (one level down): find_first_child / find_all_children.
  • Descendants: the whole subtree: find_first_descendant / find_all_descendants.
  • Ancestors: walk upwards: parent, or the tree walker below.

Descendant searches can be slow on large trees. Prefer children, or start from a closer container, when you know the structure.

ConditionFactory vs XPath

ConditionFactory XPath
Speed Very fast (native UIA query) Slower (walks the tree)
Stability High (IDs, control types) High when the path uses IDs
Strength Single-element lookups Relationships (//Tab/TabItem)
Use it for The default Structural queries

XPath

button = window.find_first_by_x_path("//Button[@AutomationId='InvokableButton']").as_button()
tabs = window.find_all_by_x_path("//Tab/TabItem")  # every tab page
checkbox = window.find_first_by_x_path("//CheckBox[@Name='Test Checkbox']").as_check_box()
var button = window.FindFirstByXPath("//Button[@AutomationId='InvokableButton']").AsButton();
var tabs = window.FindAllByXPath("//Tab/TabItem");
var checkBox = window.FindFirstByXPath("//CheckBox[@Name='Test Checkbox']").AsCheckBox();

Combining conditions

# AND: a Button whose AutomationId is "InvokableButton"
invoke = cf.by_control_type(ControlType.Button) & cf.by_automation_id("InvokableButton")

# OR: either radio button
radios = cf.by_automation_id("RadioButton1") | cf.by_automation_id("RadioButton2")

# NOT: every check box except the three-state one
two_state = cf.by_control_type(ControlType.CheckBox) & ~cf.by_automation_id("ThreeStateCheckBox")

# The same with methods: and_() / or_() / not_()
same_invoke = cf.by_control_type(ControlType.Button).and_(cf.by_automation_id("InvokableButton"))

button = window.find_first_descendant(invoke)
radio_buttons = window.find_all_descendants(radios)
check_boxes = window.find_all_descendants(two_state)
var invoke = cf.ByControlType(ControlType.Button).And(cf.ByAutomationId("InvokableButton"));
var radios = cf.ByAutomationId("RadioButton1").Or(cf.ByAutomationId("RadioButton2"));
// C#'s Not() takes no argument and negates the condition it is called on:
var twoState = cf.ByControlType(ControlType.CheckBox).And(cf.ByAutomationId("ThreeStateCheckBox").Not());

var button = window.FindFirstDescendant(invoke);
var radioButtons = window.FindAllDescendants(radios);
var checkBoxes = window.FindAllDescendants(twoState);
Python operator Python method C# Result type
a & b a.and_(b) a.And(b) AndCondition
a \| b a.or_(b) a.Or(b) OrCondition
~a a.not_() a.Not() NotCondition

Python precedence applies: ~ binds tighter than &, and & tighter than |, so a & ~b | c is (a & (~b)) | c. Add parentheses when you mean something else. Either side of & and | may also be a raw C# condition.

The C#-named And / Or / Not still work

They are kept as aliases so existing code keeps running. a.Not() with no argument negates a, like C#. a.Not(b) keeps its older Python meaning, a AND NOT b (that is, a & ~b). New code should use the operators or and_ / or_ / not_.

True and false conditions

ConditionFactory.true_condition() matches every element and ConditionFactory.false_condition() matches none. They wrap C# TrueCondition.Default and FalseCondition.Default, and you can call them without a factory instance. They are a handy neutral start when you build a condition in a loop.

# false_condition() matches nothing, so it is the neutral start for a chain of "|"
wanted = ["InvokableButton", "RadioButton1", "ThreeStateCheckBox"]
any_of = ConditionFactory.false_condition()
for automation_id in wanted:
    any_of = any_of | cf.by_automation_id(automation_id)

# true_condition() matches everything, so it is the neutral start for a chain of "&"
button_condition = ConditionFactory.true_condition() & cf.by_control_type(ControlType.Button)

found = window.find_all_descendants(any_of)
buttons = window.find_all_descendants(button_condition)
var wanted = new[] { "InvokableButton", "RadioButton1", "ThreeStateCheckBox" };
ConditionBase anyOf = FalseCondition.Default;
foreach (var automationId in wanted)
{
    anyOf = anyOf.Or(cf.ByAutomationId(automationId));
}

var buttonCondition = TrueCondition.Default.And(cf.ByControlType(ControlType.Button));

var found = window.FindAllDescendants(anyOf);
var buttons = window.FindAllDescendants(buttonCondition);

Other factory methods: by_name, by_text, by_class_name, by_help_text, by_value, by_framework_id, by_framework_type, by_process_id, by_localized_control_type. See the Condition Factory reference.

Filtering results in Python

find_all_* returns an AutomationElementCollection. It is a list with a few extra helpers (see Pythonic API):

buttons = window.find_all_descendants(cf.by_control_type(ControlType.Button))
first = buttons.first  # None when empty
enabled = buttons.filter(lambda b: b.is_enabled)
invokable = buttons.where(automation_id="InvokableButton")
var buttons = window.FindAllDescendants(cf.ByControlType(ControlType.Button));
var first = buttons.FirstOrDefault();
var enabled = buttons.Where(b => b.IsEnabled).ToArray();
var invokable = buttons.Where(b => b.AutomationId == "InvokableButton").ToArray();

Tree walking

The tree walker steps through the tree one sibling at a time. automation.tree_walker is FlaUI's raw-view ITreeWalker, so its methods take and return the raw C# elements (.raw_element).

walker = automation.tree_walker  # FlaUI ITreeWalker over the raw view
names = []
child = walker.GetFirstChild(window.raw_element)
while child is not None:
    names.append(AutomationElement(raw_element=child).control_type)
    child = walker.GetNextSibling(child)
# Most of the time the Pythonic equivalent is simpler:
children = window.find_all_children()
var walker = automation.TreeWalkerFactory.GetRawViewWalker();
var types = new List<ControlType>();
var child = walker.GetFirstChild(window);
while (child != null)
{
    types.Add(child.ControlType);
    child = walker.GetNextSibling(child);
}
var children = window.FindAllChildren();

Caching (CacheRequest)

Every property read is a cross-process call. A CacheRequest pre-fetches chosen properties for the elements found while it is active, which pays off when you read many elements at once.

from flaui.core.cache_request import CacheRequest
from flaui.core.definitions import TreeScope

cache_request = CacheRequest()
cache_request.tree_scope = TreeScope.Element
cache_request.add_property(automation.cs_automation.PropertyLibrary.Element.Name)

with cache_request.activate():
    # Elements found while the request is active come back with Name pre-fetched,
    # so reading it does not cost another cross-process call per element.
    buttons = window.find_all_descendants(cf.by_control_type(ControlType.Button))
    names = [b.name for b in buttons]
var cacheRequest = new CacheRequest { TreeScope = TreeScope.Element };
cacheRequest.Add(automation.PropertyLibrary.Element.Name);

using (cacheRequest.Activate())
{
    var buttons = window.FindAllDescendants(cf.ByControlType(ControlType.Button));
    var names = buttons.Select(b => b.Name).ToList();
}

Cache trees that don't change while you read them. Leave caching off for UI that updates live.

Retry and polling

from flaui.core.tools import Retry

# Keep trying while the lookup raises ElementNotFound; give up after 5 s.
button = Retry.WhileException(
    lambda: window.find_first_descendant(cf.by_automation_id("InvokableButton")),
    timeout=5000,
    interval=100,
    throw_on_timeout=True,
).as_button()

# Or wait for a predicate to become true.
ready = Retry.WhileFalse(lambda: button.is_enabled, timeout=2000)
var button = Retry.WhileNull(
    () => window.FindFirstDescendant(cf.ByAutomationId("InvokableButton")),
    timeout: TimeSpan.FromSeconds(5),
    interval: TimeSpan.FromMilliseconds(100),
    throwOnTimeout: true).Result.AsButton();

var ready = Retry.WhileFalse(() => button.IsEnabled, TimeSpan.FromSeconds(2)).Result;

Timeouts are milliseconds in Python

C# Retry takes TimeSpan values and returns a RetryResult<T>. The Python Retry methods take integer milliseconds and return the value directly.

Fluent assertions (expect)

Playwright-style assertions that keep polling until the condition holds or the timeout runs out. This is a Python addition with no direct C# equivalent; in C# you would combine Retry with your test framework's asserts.

from flaui.core.expectations import expect

text_box = window.find_first_descendant(cf.by_automation_id("TextBox")).as_text_box()
text_box.text = "42"

expect(text_box).to_be_visible()
expect(text_box).to_be_enabled(timeout=2000)
expect(text_box).to_have_text("42")  # to_have_value() reads `.value` (sliders, spinners, ...)
expect(text_box).not_.to_be_offscreen()
textBox.Text = "42";
Assert.That(Retry.WhileFalse(() => !textBox.IsOffscreen, TimeSpan.FromSeconds(5)).Result);
Assert.That(Retry.WhileFalse(() => textBox.IsEnabled, TimeSpan.FromSeconds(2)).Result);
Assert.That(Retry.WhileFalse(() => textBox.Text == "42", TimeSpan.FromSeconds(5)).Result);

Input timing (post_wait)

Mouse methods, click, TextBox.enter and Tab.select_tab_item accept post_wait: True (~100 ms), a number of seconds, or a callable.

from flaui.core.input import Mouse

text_box = window.find_first_descendant(cf.by_automation_id("TextBox"))
Mouse.click(text_box.get_clickable_point(), post_wait=True)  # ~100 ms
text_box.as_text_box().enter("typed", post_wait=0.25)  # 250 ms
Mouse.Click(textBox.GetClickablePoint());
Wait.UntilInputIsProcessed();
textBox.AsTextBox().Enter("typed");
Thread.Sleep(250);

Exception translation

Every method that crosses into C# is decorated with @handle_csharp_exceptions, which turns .NET exceptions into the Python exception hierarchy. For example, a missing element raises ElementNotFound, and an unsupported pattern raises PatternNotSupportedException. Catch those, not System.Exception. If you add a new wrapper method, give it the same decorator.

Page objects

Group element look-ups in a small class that mirrors your app's screens. The project's own suite does this in tests/test_utilities/elements/:

class SimpleControls:
    """Element accessors for the Simple Controls tab."""

    def __init__(self, window: Window, cf: ConditionFactory) -> None:
        self._window, self._cf = window, cf

    @property
    def invoke_button(self) -> Button:
        return self._window.find_first_descendant(self._cf.by_automation_id("InvokableButton")).as_button()
public class SimpleControls(Window window, ConditionFactory cf)
{
    public Button InvokeButton =>
        window.FindFirstDescendant(cf.ByAutomationId("InvokableButton")).AsButton();
}

Inspection tools

  • FlaUInspect: best for exploring patterns and properties. It uses the same FlaUI engine.
  • Accessibility Insights: quick property look-ups and accessibility checks.

How the bridge works

graph LR
    A["Python code"] --> B["setup_pythonnet_bridge()"]
    B --> C["PythonNet CLR"]
    C --> D["FlaUI DLLs<br/>(Core, UIA2, UIA3)"]
    D --> E["Windows UI Automation API"]

When to use what

  • ConditionFactory: fast, stable lookups by ID or control type. This is the default.
  • XPath: relationships between elements and structural queries.
  • Tree walker: step-by-step traversal when you know the structure.
  • CacheRequest: reading many properties from a tree that isn't changing.
  • Retry / expect: slow dialogs, asynchronous content, and assertions that need to wait.