WebdriverIO与JavaScript:如何通过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 samenameattribute 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.
- First name input:
Combine with Other Attributes for Precision
If your inputs have additional unique attributes (likeplaceholder,class, or associated label text), pair those with thenameattribute 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']
- First name input with placeholder "First Name":
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']
- First name input in a "first-name-container" parent:
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. AssignfirstNameIDto the first name input andlastNameIDto the last name input. This simplifies your selectors (e.g.,//*[@name='firstNameID']) and eliminates risks from UI reordering.
内容的提问来源于stack exchange,提问作者Matt Y

