You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Selenium Java中的指定按钮创建唯一XPath?

Reliable XPath Locators for Your Selenium Button

Here are several robust XPath options to target your specific button, avoiding conflicts with elements sharing the same mantine-qo1k2 mantine-Button-label class:

1. Target by the unique data-track attribute

This is the most reliable option since the data-track attribute contains a unique tracking identifier (sales_invoice_add_item_button) that's unlikely to be reused elsewhere.

XPath:

//button[contains(@data-track, 'sales_invoice_add_item_button')]

Java Code:

driver.findElement(By.xpath("//button[contains(@data-track, 'sales_invoice_add_item_button')]")).click();

For an exact match (if the data-track value never changes):

//button[@data-track='{"name":"sales_invoice_add_item_button","type":"create_invoice"}']
driver.findElement(By.xpath("//button[@data-track='{\"name\":\"sales_invoice_add_item_button\",\"type\":\"create_invoice\"}']")).click();

(Note: Escape double quotes with backslashes in Java string literals.)

2. Target by button text (with ancestor relationship)

If the button's text "Add items from database" is unique to this button, you can locate the span with the text and traverse up to its parent button:

XPath:

//span[text()='Add items from database']/ancestor::button[1]

Java Code:

driver.findElement(By.xpath("//span[text()='Add items from database']/ancestor::button[1]")).click();

3. Combine class attributes + text for specificity

Use less common class attributes on the button (like secondary-button or event-track) along with the text to narrow down the element:

XPath:

//button[contains(@class, 'secondary-button') and .//span[text()='Add items from database']]

Java Code:

driver.findElement(By.xpath("//button[contains(@class, 'secondary-button') and .//span[text()='Add items from database']]")).click();

Recommendation

Prioritize the data-track based locator first—it's designed for tracking purposes and is less prone to changes from UI updates compared to class names or visible text.

内容的提问来源于stack exchange,提问作者Fayaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:13:18