Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Click the tree’s semantic disclosure control, not its decorative arrow, then wait for the expanded state. In most accessible trees the reliable pattern is a closed parent selected with [role='treeitem'][aria-expanded='false'], a nested button or [role='button'], and an explicit wait until aria-expanded becomes true (or a child group is visible). This approach is more stable than an absolute XPath or a fixed sleep.

How tree expansion works

A tree view is a hierarchical list. Parent nodes reveal or hide descendants; leaf nodes have no descendants to reveal. In the WAI-ARIA tree pattern, a parent treeitem exposes aria-expanded="false" when closed and aria-expanded="true" when open. A leaf normally omits aria-expanded. Some libraries put that state on a row or cell in a treegrid instead, so inspect the actual DOM rather than assuming one markup shape.

The visible chevron may be an SVG, a span, or a CSS pseudo-element. It is often decorative and may not be the element receiving the click. Prefer the semantic parent or its disclosure button. After clicking, verify a UI state change; a returned click() call only means Selenium issued the interaction.

Inspect the DOM and choose a locator

Prefer stable attributes

  1. Open browser developer tools and inspect the closed branch.
  2. Look for a unique id. Selenium generally recommends a unique ID when one exists.
  3. If there is no ID, use a stable data-testid, component attribute, role/state combination, or concise CSS selector.
  4. Confirm which element is clickable: the treeitem, a nested disclosure button, or an element with role="button".

A useful generic locator is *[role='treeitem'][aria-expanded='false']. Narrow it to the intended tree container and label so that a similarly named branch elsewhere cannot be opened accidentally. Avoid absolute paths such as /html/body/div[2]/...; layout wrappers and framework renders routinely change them.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Logitech M185 Compact Ambidextrous 2.4 GHz Wireless Mouse - Swift Grey
  • Compact Mouse: With a comfortable and contoured shape, this Logitech ambidextrous wireless mouse feels great in either right or left hand and is far superior to a touchpad
  • Durable and Reliable: This USB wireless mouse features a line-by-line scroll wheel, up to 1 year of battery life (2) thanks to a smart sleep mode function, and comes with the included AA battery
  • Universal Compatibility: Your Logitech mouse works with your Windows PC, Mac, or laptop, so no matter what type of computer you own today or buy tomorrow your mouse will be compatible
  • Plug and Play Simplicity: Just plug in the tiny nano USB receiver and start working in seconds with a strong, reliable connection to your wireless computer mouse up to 33 feet / 10 m (5)
  • Better than touchpad: Get more done by adding M185 to your laptop; according to a recent study, laptop users who chose this mouse over a touchpad were 50% more productive (3) and worked 30% faster (4)

Scope by tree and label

If the page contains several trees, first locate the relevant container (for example, an element with role="tree"), then search inside it. For a known label, locate the treeitem containing that label and then its own disclosure control. Do not select the first matching arrow globally.

Python: click an ARIA-aware expand control

This example finds a closed parent, prefers a nested button, clicks it, and waits for the state transition. Replace the generic selector with the attributes from your page.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)

parent = wait.until(EC.presence_of_element_located(
    (By.CSS_SELECTOR, "[role='treeitem'][aria-expanded='false']")
))

# A nested disclosure control is preferable to a decorative SVG or span.
controls = parent.find_elements(By.CSS_SELECTOR, "button, [role='button']")
control = controls[0] if controls else parent

wait.until(lambda d: control.is_displayed() and control.is_enabled())
control.click()
wait.until(lambda d: parent.get_attribute("aria-expanded") == "true")

presence_of_element_located only proves that the node exists in the DOM. The second wait checks visibility and enabled state, and the final wait checks the postcondition. If the framework replaces the node while rendering, re-find it before the final assertion (see troubleshooting below).

Python: target a named branch and wait for its children

When several branches are closed, include the visible label in the locator. The following XPath looks for a treeitem whose descendant span contains “Reports,” then waits for the child group.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
parent = wait.until(EC.presence_of_element_located(
    (By.XPATH,
     "//li[@role='treeitem' and @aria-expanded='false']"
     "[.//span[normalize-space()='Reports']]" )
))

parent.find_element(By.CSS_SELECTOR, "button, [role='button']").click()
wait.until(lambda d: parent.get_attribute("aria-expanded") == "true")
child_group = wait.until(
    lambda d: parent.find_element(By.CSS_SELECTOR, "[role='group']")
)
wait.until(lambda d: child_group.is_displayed())

Markup varies: the label may be a link, text node, or element with a different class, and the child container may not use role="group". Adapt the label and child selector to the inspected DOM. If children are loaded over the network, waiting for the rendered child or a loading indicator to disappear is more meaningful than waiting a fixed number of seconds.

Rank #2
Sale
Logitech G305 Lightspeed Wireless Gaming Mouse - Black
  • The next-generation optical HERO sensor delivers incredible performance and up to 10x the power efficiency over previous generations, with 400 IPS precision and up to 12,000 DPI sensitivity
  • Ultra-fast LIGHTSPEED wireless technology gives you a lag-free gaming experience, delivering incredible responsiveness and reliability with 1 ms report rate for competition-level performance
  • G305 wireless mouse boasts an incredible 250 hours of continuous gameplay on just 1 AA battery; switch to Endurance mode via Logitech G HUB software and extend battery life up to 9 months
  • Wireless does not have to mean heavy, G305 lightweight mouse provides high maneuverability coming in at only 3.4 oz thanks to efficient lightweight mechanical design and ultra-efficient battery usage
  • The durable, compact design with built-in nano receiver storage makes G305 not just a great portable desktop mouse, but also a great laptop travel companion, use with a gaming laptop and play anywhere

Java: the equivalent WebDriver interaction

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
By closedParent = By.cssSelector("[role='treeitem'][aria-expanded='false']");
WebElement parent = wait.until(
    ExpectedConditions.presenceOfElementLocated(closedParent));

WebElement control = parent.findElements(
    By.cssSelector("button,[role='button']"))
    .stream().findFirst().orElse(parent);

wait.until(d -> control.isDisplayed() && control.isEnabled());
control.click();
wait.until(d -> "true".equals(parent.getDomAttribute("aria-expanded")));

Import java.time.Duration and the Selenium classes used by your project. If your Selenium version does not provide getDomAttribute, use the corresponding attribute accessor available in that version.

Wait for a real expansion condition

State attribute

For an ARIA tree, wait for aria-expanded="true". This is fast and unambiguous when the widget updates the attribute synchronously.

Child visibility

Some components update the attribute before inserting descendants. Wait for the child group, a known child label, or another element that represents the completed render. Conversely, a component may reveal children with CSS while leaving the state on a row rather than the treeitem; inspect and assert the attribute on the element that owns it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Network-rendered branches

For lazy-loaded data, combine the state check with a child condition or a loading-state condition. Re-find elements after the render because virtual-DOM frameworks can detach the old node and create a replacement.

Selenium explicit waits poll until a condition is true. Prefer them to arbitrary sleeps, and do not mix implicit and explicit waits: the two polling systems can compound delays and make timing unpredictable.

Rank #3
Sale
Logitech M185 Compact Ambidextrous Wireless Mouse with Rubber Grips - Blue
  • Compact Mouse: With a comfortable and contoured shape, this Logitech ambidextrous wireless mouse feels great in either right or left hand and is far superior to a touchpad
  • Durable and Reliable: This USB wireless mouse features a line-by-line scroll wheel, up to 1 year of battery life (2) thanks to a smart sleep mode function, and comes with the included AA battery
  • Universal Compatibility: Your Logitech mouse works with your Windows PC, Mac, or laptop, so no matter what type of computer you own today or buy tomorrow your mouse will be compatible
  • Plug and Play Simplicity: Just plug in the tiny nano USB receiver and start working in seconds with a strong, reliable connection to your wireless computer mouse up to 33 feet / 10 m (5)
  • Better than touchpad: Get more done by adding M185 to your laptop; according to a recent study, laptop users who chose this mouse over a touchpad were 50% more productive (3) and worked 30% faster (4)

When a normal click is intercepted or ineffective

Use the semantic target

If clicking an SVG path or decorative span does nothing, click the nested disclosure button or the parent control. The semantic element is more likely to have the correct event listener, hit area, and accessibility state.

Handle overlays and geometry

For sticky headers, cookie dialogs, animations, or another overlay, wait for the obstruction to disappear and scroll only when necessary. Then retry the native click. If the interaction depends on pointer position, hover, focus, or wheel input, use Selenium’s Actions API, which supplies lower-level virtualized device input.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from selenium.webdriver.common.action_chains import ActionChains

ActionChains(driver).move_to_element(control).click().perform()
wait.until(lambda d: parent.get_attribute("aria-expanded") == "true")

Use the keyboard when the widget supports it

Focus the parent node and send ENTER when the tree implements the documented keyboard behavior. This exercises the same accessible activation path a keyboard user can use and avoids fragile pointer geometry.

from selenium.webdriver.common.keys import Keys

parent.send_keys(Keys.ENTER)
wait.until(lambda d: parent.get_attribute("aria-expanded") == "true")

JavaScript click is diagnostic, not a default fix

arguments[0].click() can reveal whether an event handler responds, but it bypasses native hit-testing and the user-input path your test is intended to exercise. Use it only to diagnose an application issue, not to hide a real overlay or locator problem.

Common failures and precise fixes

Symptom Likely cause Fix
NoSuchElementException The tree is not rendered yet, or the branch appears after another action. Wait for the tree or branch explicitly; verify the current frame and the locator in the live DOM.
ElementClickInterceptedException An overlay, sticky header, or animation covers the control. Wait for the overlay/animation, scroll if needed, then use a native click or Actions when pointer geometry matters.
StaleElementReferenceException The framework replaced the treeitem during expansion. Locate the parent again and perform the postcondition wait against the fresh element.
Click returns but no children appear You clicked a leaf, the wrong element, or expansion is still rendering. Check that the node is a parent, assert aria-expanded, and wait for a child group or known child node.
The wrong branch opens A document-wide selector matched another tree or label. Scope to the intended role="tree" container and include the visible label or a stable data attribute.
Flaky timing Fixed sleeps or mixed implicit/explicit waits. Remove sleeps, use a state-based explicit condition, and configure one synchronization strategy.

Designing maintainable tree tests

  • Ask developers to expose stable IDs or data-testid values for tree containers and disclosure buttons.
  • Keep a locator for the semantic control separate from a locator for the postcondition; this makes failures explainable.
  • Assert that a leaf omits expansion state and that a parent transitions from false to true.
  • Test repeated expand/collapse operations and branches loaded lazily, not only the first visible node.
  • Capture diagnostic HTML or a screenshot on failure, but do not replace state assertions with visual inspection.

Or skip the browser setup

If your goal is to obtain a screenshot after a tree interaction rather than drive Selenium itself, ScreenshotNeo provides a website screenshot API. Its GET endpoint can return PNG, JPEG, WebP, or PDF; options include custom JavaScript, clicking an element, waiting for a selector or network idle, full-page capture, and hiding selectors. Before capture it accepts consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result.

Read the complete parameters in the ScreenshotNeo documentation. A one-call cURL example is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/tree -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com/tree"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com/tree' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots, and every feature is included on every plan. Create a free ScreenshotNeo account.

Rank #4
Amazon Basics 3-Button USB Wired Mouse with Responsive Tracking, Plug & Play, Compatible with Windows and Mac, Black
  • Computer mouse for easily navigating a computer interface; click, scroll, and more
  • USB-A wired connection; if existing device only supports USB-C, an additional adapter will be required
  • High-definition (1000 dpi) optical tracking ensures responsive cursor control for precise tracking and easy text selection
  • 3 buttons offer effortless fingertip control
  • Plug-and-go ready for instant use
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost considerations

Use the narrowest locator that remains stable. A unique ID or scoped CSS selector is typically cheaper to evaluate and easier to debug than a long structural XPath. Keep explicit timeouts long enough for the slowest supported environment, but avoid a global multi-minute timeout that masks a broken branch.

For large virtualized trees, only visible nodes may exist in the DOM. Scroll or expand ancestors first, then locate the newly rendered descendant. For animations, synchronize on the final state rather than elapsed time. When a test fails, record the current URL, tree markup, expansion attribute, and screenshot so you can distinguish a locator regression from a backend or rendering delay.

FAQ

Should I click the arrow icon or the folder label?

Use whichever element the widget defines as its disclosure control. The folder label may select the node or navigate elsewhere, while a nested button may exclusively toggle children; inspect event behavior and semantics instead of guessing from appearance.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How can I tell whether a node is a leaf before clicking?

Check whether it has descendants or a disclosure control and whether it exposes aria-expanded. A conforming leaf treeitem normally omits that attribute, so there is no expansion state to wait for.

Why does the element become stale immediately after the click?

Many component frameworks rebuild the row when children are inserted. Treat the old reference as disposable: locate the branch again and apply your assertion to the replacement element.

Best Value
Sale
Acer Wireless Mouse for Laptop, 2.4GHz Computer Mouse 3 Adjustable 1600 DPI
  • 【Plug and Play for Home/Office/School】The wireless computer mouse features 2.4GHz connectivity, delivering a stable, interference-free connection up to 32ft. Designed for 𝐦𝐞𝐝𝐢𝐮𝐦 𝐭𝐨 𝐥𝐚𝐫𝐠𝐞 𝐬𝐢𝐳𝐞𝐝 𝐡𝐚𝐧𝐝𝐬, it ensures comfortable use all day. Simply plug in the USB-A receiver for instant pairing—no drivers needed. 📌📌 If the mouse isn’t suitable, place the USB receiver in the battery compartment and return both.
  • 【3 Levels Adjustable DPI】This travel USB mouse offers 3 adjustable DPI settings (800, 1200, 1600), allowing you to customize sensitivity for precise design work. Effortlessly switch to match your task and elevate your productivity. 📌 Please remove the film at the bottom of the mouse before use.
  • 【Effortless Browsing】Equipped with forward and backward buttons, this computer mice streamlines your workflow, making it easy to navigate through web pages and files with a simple click. 📌Side button does not work on Mac.
  • 【Visible Indicator Light】 The pc mouse features a visual indicator for DPI levels and low battery alerts. The red light flashes once for 800 DPI, twice for 1200 DPI, and three times for 1600 DPI. When the battery level is below 10%, the light flashes red until the mouse is completely out of power.
  • 【Click to Wake】With smart sleep mode, it saves power by standby after 10 inactive minutes, just 2-3 clicks to wake. This efficient design delivers 3x longer battery life than motion-wake mice. Engineered for durability, its buttons and scroll wheel are tested for 10 million clicks, ensuring long-term reliability and consistent performance.

Frequently Asked Questions

Should I click the arrow icon or the folder label?

Use the element the widget defines as its disclosure control; a label may select or navigate, while a nested button may only toggle children.

How can I tell whether a node is a leaf before clicking?

Inspect for descendants, a disclosure control, and an aria-expanded attribute. A conforming leaf normally omits that attribute.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does the element become stale immediately after the click?

Frameworks often rebuild the row during rendering. Re-locate the branch after clicking and assert the state on the replacement element.

The Bottom Line

Stable semantic locators, explicit waits, and a verified expansion state make Selenium tree interactions reliable. Click the disclosure control, scope it to the correct branch, and assert the rendered result.

Quick Recap

SaleBestseller No. 1
Logitech M185 Compact Ambidextrous 2.4 GHz Wireless Mouse - Swift Grey
Logitech M185 Compact Ambidextrous 2.4 GHz Wireless Mouse - Swift Grey
Product carbon footprint: 3.97 kg CO2e; Contoured shape: Gives you more comfort and control
$14.90
SaleBestseller No. 3
Bestseller No. 4
Amazon Basics 3-Button USB Wired Mouse with Responsive Tracking, Plug & Play, Compatible with Windows and Mac, Black
Amazon Basics 3-Button USB Wired Mouse with Responsive Tracking, Plug & Play, Compatible with Windows and Mac, Black
Computer mouse for easily navigating a computer interface; click, scroll, and more; 3 buttons offer effortless fingertip control
$9.70

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.