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

WebdriverIO与JavaScript:如何通过name访问同标识的两个输入框?

How to Target Duplicate Accessibility Identifiers by Name

Hey Matt, let's break this down for you. First off, having two elements share the same accessibility identifier (nameID) isn't ideal for long-term reliability, but we can work with what you've got to get the expected results. Here's how to properly access these inputs using the name attribute:

  • Fix the Indexed Selector Syntax
    It looks like your original selector has a syntax error with parentheses placement. If you're using XPath (common in UI automation tools like Appium, Selenium, or XCUITest), the correct way to target the nth element with the same name attribute is to wrap the entire matching query in parentheses first, then append the index. For example:

    • First name input: (//*[@name='nameID'])[1]
    • Last name input: (//*[@name='nameID'])[2]
      Note: XPath indexes start at 1 (not 0), and the order matches how elements appear in your app's DOM/UI hierarchy. Double-check which index maps to first vs last name by inspecting your app's element tree.
  • Combine with Other Attributes for Precision
    If your inputs have additional unique attributes (like placeholder, class, or associated label text), pair those with the name attribute to avoid relying on indexes (which can break if the UI layout changes). Examples:

    • First name input with placeholder "First Name": //*[@name='nameID' and @placeholder='First Name']
    • Last name input linked to a "Last Name" label: //label[text()='Last Name']//following-sibling::*[@name='nameID']
  • Leverage Parent/Sibling Elements
    If the two inputs live inside different parent containers (like separate form groups), target the parent first then drill down to the input. This avoids index dependency entirely:

    • First name input in a "first-name-container" parent: //div[@class='first-name-container']//*[@name='nameID']
    • Last name input in a "last-name-container" parent: //div[@class='last-name-container']//*[@name='nameID']
  • Best Practice: Use Unique Identifiers
    While the above fixes work, the most reliable long-term solution is to update your accessibility identifiers to be unique. Assign firstNameID to the first name input and lastNameID to the last name input. This simplifies your selectors (e.g., //*[@name='firstNameID']) and eliminates risks from UI reordering.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:28:20