如何在AngularJS中使用Protractor唯一识别相同元素
Hey there! Let's figure out how to uniquely target those two identical "select node" buttons—this is such a common hurdle when working with DOM selection or UI automation, so you're not alone here!
Here are practical, actionable ways to distinguish between them:
More often than not, even if the buttons have the exact same text, their parent elements will have unique identifiers (like id, class, or custom data-* attributes). For example:
- If one button lives inside a
<div>withid="source-panel"and the other inid="target-panel", use these combined selectors:- CSS:
#source-panel button:has-text("select node")(modern browsers support:has-text, or use jQuery's:containsif you're using it) - XPath:
//div[@id='source-panel']//button[text()='select node']
- CSS:
If the buttons sit next to unique labels, inputs, or other elements, use those as reference points. Say one button is paired with a label that reads "Source Node" and the other with "Target Node":
- XPath:
//label[text()='Source Node']/following-sibling::button[text()='select node'] - CSS:
label:has-text("Source Node") + button(uses adjacent sibling selector+)
If you can't find any unique surrounding attributes, you can target by the button's position in the DOM. Just keep in mind: this breaks easily if the UI structure changes, so only use it if nothing else works.
- CSS:
button:has-text("select node"):nth-of-type(1)(first button) or:nth-of-type(2)(second) - XPath:
(//button[text()='select node'])[1](XPath indexes start at 1)
Pop open your browser's dev tools (F12) and inspect both buttons—you might spot unique hidden attributes like data-testid, data-node-id, or even different class values. For example:
- CSS:
button[data-testid="source-select-btn"] - XPath:
//button[@data-node-id='123' and text()='select node']
If the buttons share some attributes but differ in others (like class or type), mix those with the text to narrow it down. Suppose one has class="primary" and the other class="secondary":
- CSS:
button.primary:has-text("select node") - XPath:
//button[@class='secondary' and text()='select node']
Pro tip: Always prioritize selectors that use stable, purpose-built attributes (like data-testid) over position-based ones—they're way more resilient to UI updates!
内容的提问来源于stack exchange,提问作者Diva

