Implementation:Microsoft Playwright LocatorParser
Overview
LocatorParser parses locator strings from various programming languages (JavaScript, Python, Java, C#) back into Playwright selectors, enabling the codegen and inspector tools to work with human-readable locator expressions.
Description
The parseLocator function takes a locator expression written in any supported language and converts it back into a Playwright internal selector string. It handles:
- Template string parsing with escape sequence support
- Regular expression literal parsing
- Language-specific method names (e.g.,
getByRolevsget_by_role) - Role enum values (e.g.,
AriaRole.Buttonto'button') - Quote style detection for round-trip fidelity
The parser uses a template-based approach where string literals are extracted and replaced with placeholders, then the template is matched against known locator patterns.
Usage
Used by the codegen/inspector tool to parse locator expressions entered by users.
Code Reference
Source Location
packages/playwright-core/src/utils/isomorphic/locatorParser.ts (248 lines)
Function Signature
function parseLocator(locator: string, testIdAttributeName: string): {
selector: string;
preferredQuote: Quote | undefined;
};
Import
import { parseLocator } from '../utils/isomorphic/locatorParser';
I/O Contract
Inputs
locator: string-- locator expression in any supported languagetestIdAttributeName: string-- the configured test ID attribute
Outputs
selector: string-- internal Playwright selector stringpreferredQuote-- the quote style used in the original expression
Supported Patterns
getByRole,getByText,getByLabel,getByPlaceholdergetByAltText,getByTitle,getByTestIdlocatorwith CSS selectors- Chained locators with
.filter(),.nth(), etc.
Related Pages
- Microsoft_Playwright_CssParser -- CSS selector parsing
- Microsoft_Playwright_Server_Selectors -- Selector engine registry
- Microsoft_Playwright_StringUtils -- String escaping utilities