I’m working on automating a web app and need to find input fields by their associated labels. The goal is to create a helper function that takes a partial label text and locates the corresponding input field.
The problem is that I only know part of the label text, not the complete string. For example, I might know “Name” but the actual label could be “Full Name” or “Name (Required)” or “First Name”.
I also tried using the text selector:
fieldSelector = `::-p-text(${partialLabel})`;
But this targets the label element itself instead of the input field I need to interact with.
The application uses Angular and follows WCAG 2.0 standards. Is there a way to create a selector that can match partial label text and still point to the actual input element? I need something generic that works regardless of the exact label wording.
I’ve hit this same issue scraping forms with dynamic labels. Best approach I’ve found is using the for attribute that links labels to inputs. Find the label with your partial text, grab its for value, then target the input with that ID.
This method stays solid even when the label structure shifts since it uses the actual HTML relationship instead of DOM positioning. Most accessible forms use proper label-input connections, so your Angular app should work fine with this.
try combining xpath with puppeteer - await page.$x("//label[contains(text(), 'Name')]//following::input[1]") works great for partial matching. the contains() function handles this stuff well and grabs the next input after finding your partial label match.
Why not try aria-labelledby instead of the for attribute? A lot of Angular apps use ARIA relationships instead of standard HTML label associations. Find elements with your partial text first, grab their ID, then use that to locate the input field. Try const labelId = await page.$eval('*:has-text("Name")', el => el.id) then await page.$([aria-labelledby*=“${labelId}”]). This works when multiple elements make up an input’s accessible name - happens all the time in apps that follow WCAG guidelines.