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

如何在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:

1. Target via Parent/Ancestor Container Attributes

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> with id="source-panel" and the other in id="target-panel", use these combined selectors:
    • CSS: #source-panel button:has-text("select node") (modern browsers support :has-text, or use jQuery's :contains if you're using it)
    • XPath: //div[@id='source-panel']//button[text()='select node']
2. Anchor to Sibling/Adjacent Unique Elements

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 +)
3. Use Index Position (Last Resort!)

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)
4. Look for Hidden Unique Attributes

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']
5. Combine Multiple Attributes

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:41:15