如何为Selenium Java中的指定按钮创建唯一XPath?
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

