3 Ways I Use AI to Auto-Generate Playwright Locators
If you've maintained a Playwright suite for more than a few months, you know the real cost isn't writing tests — it's the constant locator rot. A designer tweaks a class name, a component gets refactored, and suddenly a dozen tests are red for reasons that have nothing to do with actual bugs. After 18 years in test automation — including building enterprise-scale frameworks — I've found that…
Maintaining a Playwright test suite over an extended period can be costly due to the constant need to update locators. Refactoring components or class names can cause a dozen tests to fail, unrelated to actual bugs. Leveraging AI for locator generation has proven to be highly beneficial in reducing this locator rot. Here are three ways the author integrates AI into their workflow:
1. AI-Assisted Locator Discovery from the DOM: Instead of manually selecting a data-testid or dealing with fragile CSS selectors, the author feeds a snapshot of the relevant DOM section to an LLM. The AI proposes the most resilient locator strategy, favoring accessible roles and text over implementation-specific attributes. For instance, rather than manually creating a selector like const button = page.locator('.btn.btn-primary.mt-2.submit-btn-v2'); the AI might suggest a more resilient option such as const button = page.getByRole('button', {name: 'Submit Order'}); This approach encourages the use of Playwright's built-in resilient locator patterns rather than relying on CSS-selector habits that may arise under time constraints.
2. Self-Healing Locators via Fallback Chains: When a primary locator fails during a test run, rather than causing the entire test to fail, the author uses an AI step to analyze the current DOM and suggest a fallback locator that matches the original intent of the interaction. The AI flags the suggestion and logs the change, requiring human confirmation before updating the test suite.
This method doesn't result in "magic self-healing" that might mask real regressions. Instead, it provides a flagged suggestion for confirmation, allowing testers to address the issue and maintain the quality of their test suite.
3. Locator Generation from Natural-Language Test Steps: For teams writing BDD-style scenarios (e.g., "User clicks the 'Add to Cart' button"), the author uses AI to translate the natural language directly into a first-draft Playwright locator and action. The AI generates a suggested locator and action, such as await page.getByRole('button', {name: 'Add to Cart'}).click(); which a human then reviews and commits.
This approach significantly speeds up onboarding for less-experienced testers, enabling them to focus on writing test intent rather than wrestling with Playwright's API surface on day one.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.
