Skip to main content

Analyze DOM elements and generate ranked Playwright selector recommendations.

Project description

Playwright Inspector

Playwright Inspector

Intelligent Selector Recommendation Engine for Playwright

Inspect โ€ข Analyze โ€ข Recommend

Python 3.11+ Playwright 1.61+ Tests License MIT Version 1.0.0

๐Ÿ‡ฌ๐Ÿ‡ง English ยท ๐Ÿ‡ซ๐Ÿ‡ท Franรงais


Every DOM element can be located in multiple ways

Playwright Inspector tells you which one you should use.

Playwright Inspector analyzes a DOM element, evaluates the available Playwright locator strategies and recommends the selector that an experienced Playwright developer would naturally choose.

Instead of relying on intuition, personal preference or trial and error, every recommendation is based on measurable quality criteria.


Why Playwright Inspector?

Modern web applications often expose several ways to locate the same element.

Should you use:

page.get_by_role(...)

or:

page.get_by_label(...)

or:

page.get_by_placeholder(...)

or:

page.locator(...)

The answer is not always obvious.

Choosing an unsuitable locator can lead to:

  • brittle automated tests;
  • unnecessary maintenance;
  • inconsistent coding practices;
  • difficult debugging after user-interface changes;
  • selectors that unexpectedly match several elements.

Playwright already provides excellent locator strategies.

The real challenge is knowing which strategy is the most reliable for a particular element.

Playwright Inspector solves that problem by inspecting the target element, analyzing its context, generating viable Playwright strategies and ranking them according to objective quality measurements.


Why is it different?

Playwright Inspector does not replace Playwright.

It helps developers use Playwright at its best.

Traditional selector tools usually generate one or more locators. Playwright Inspector goes further by evaluating each candidate before recommending it.

The analysis considers:

  • accessibility information;
  • selector uniqueness;
  • element visibility;
  • selector stability;
  • DOM hierarchy;
  • iframe context;
  • nested iframe context;
  • open Shadow DOM context.

The result is a ranked collection of recommendations, each accompanied by a confidence score, strengths and warnings.


Live example

Suppose you inspect the following element:

<label for="search-box">Search</label>

<input
    id="search-box"
    name="q"
    type="search"
    placeholder="Search products"
    data-testid="search-field"
>

Several Playwright strategies can target it.

A typical ranked result may look like this:

Rank Recommendation Confidence
โ˜…โ˜…โ˜…โ˜…โ˜… page.get_by_role("searchbox", name="Search") 98 / 100
โ˜…โ˜…โ˜…โ˜…โ˜… page.get_by_label("Search") 95 / 100
โ˜…โ˜…โ˜…โ˜…โ˜… page.get_by_placeholder("Search products") 92 / 100
โ˜…โ˜…โ˜…โ˜…โ˜† page.get_by_test_id("search-field") 88 / 100
โ˜…โ˜…โ˜…โ˜†โ˜† page.locator("#search-box") 73 / 100
โ˜…โ˜†โ˜†โ˜†โ˜† page.locator("input") 28 / 100

Every recommendation may include:

  • a confidence score;
  • a uniqueness result;
  • a visibility result;
  • a stability result;
  • detected strengths;
  • potential weaknesses.

Playwright Inspector does not remove developer judgment. It provides the information needed to make a better decision.


Features

Capability Description
Intelligent recommendations Generates and evaluates multiple Playwright locator strategies.
Confidence score Assigns a normalized quality score from 0 to 100.
Accessibility-first selection Prioritizes user-facing Playwright locators whenever possible.
Uniqueness analysis Determines whether the selector matches exactly one element.
Visibility analysis Checks whether the first matching element is visible.
Stability analysis Detects fragile IDs, generated classes and overly broad selectors.
iframe support Builds selectors for elements inside iframes.
Nested iframe support Preserves the complete frame hierarchy.
Shadow DOM support Handles elements located inside open Shadow DOM trees.
Structured results Returns an InspectionResult rather than unstructured output.
Public Python API Integrates easily into existing Playwright projects and tools.
Automated tests Includes unit and integration coverage for the core behavior.

Installation from GitHub

The first release is distributed through GitHub.

Clone the repository:

git clone https://github.com/YOUR-ACCOUNT/playwright-inspector.git
cd playwright-inspector

Install the project:

python -m pip install -e .

For development, install the optional test dependencies:

python -m pip install -e ".[dev]"

Install the Playwright Chromium browser if it is not already available:

python -m playwright install chromium

Requirements

  • Python 3.11 or newer;
  • Playwright 1.61 or newer.

Replace YOUR-ACCOUNT with the final GitHub account or organization name when the repository is created.


Quick start

from playwright.sync_api import sync_playwright

from playwright_inspector import Inspector


with sync_playwright() as playwright:
    browser = playwright.chromium.launch(
        headless=True,
    )

    page = browser.new_page()
    page.set_content(
        """
        <button
            id="login-button"
            type="button"
        >
            Login
        </button>
        """
    )

    inspector = Inspector(page)

    result = inspector.inspect(
        page.locator("#login-button")
    )

    if result.best is not None:
        print(result.best.selector)
        print(result.best.score)
        print(result.best.stars)

    print(result.summary())

    browser.close()

Typical output:

page.get_by_role("button", name="Login")
93
โ˜…โ˜…โ˜…โ˜…โ˜…

3 selector candidate(s). Best: page.get_by_role("button", name="Login") (93/100, โ˜…โ˜…โ˜…โ˜…โ˜…)

Public API

Playwright Inspector exposes a deliberately small public API.

Inspector

Inspector is the main entry point.

from playwright_inspector import Inspector

inspector = Inspector(page)

result = inspector.inspect(
    page.locator("#login-button")
)

The supplied locator must match exactly one element.

The method raises:

  • LookupError when no element is found;
  • ValueError when several elements are matched;
  • TypeError when the argument is not a Playwright Locator.

InspectionResult

InspectionResult contains the ranked recommendations.

best = result.best
score = result.best_score
summary = result.summary()

It also supports iteration:

for candidate in result:
    print(
        candidate.stars,
        candidate.selector,
        candidate.confidence,
    )

Useful properties include:

  • best;
  • best_score;
  • is_empty;
  • unique_candidates;
  • visible_candidates;
  • stable_candidates.

SelectorCandidate

Each candidate contains the generated selector and its analysis results.

candidate.selector
candidate.score
candidate.reason

candidate.match_count
candidate.is_unique
candidate.is_visible
candidate.is_stable

candidate.strengths
candidate.warnings

Display helpers are also available:

candidate.stars
candidate.confidence
candidate.uniqueness_status
candidate.visibility_status
candidate.stability_status

How it works

The public Inspector coordinates the complete inspection workflow.

Playwright Locator
        โ”‚
        โ–ผ
ElementInspector
        โ”‚
        โ–ผ
AccessibleInspector
        โ”‚
        โ–ผ
DomPathAnalyzer
        โ”‚
        โ–ผ
SelectorGenerator
        โ”‚
        โ–ผ
SelectorContextApplier
        โ”‚
        โ–ผ
SelectorPipeline
        โ”‚
        โ–ผ
SelectorAnalyzer
        โ”‚
        โ–ผ
InspectionResult

Each component has one primary responsibility:

Component Responsibility
ElementInspector Extracts DOM properties from the inspected element.
AccessibleInspector Resolves role and accessible-name information.
DomPathAnalyzer Detects iframe and Shadow DOM traversal steps.
SelectorGenerator Produces candidate Playwright selectors.
SelectorContextApplier Applies the required DOM access path.
SelectorAnalyzer Evaluates candidates against the current page.
SelectorPipeline Analyzes and ranks the recommendations.
InspectionResult Exposes the final result through a structured API.

Selector quality analysis

Each generated locator is evaluated using measurable criteria.

Strategy quality

User-facing Playwright locators receive stronger initial scores than generic CSS locators.

Examples include:

  • get_by_role;
  • get_by_label;
  • get_by_alt_text;
  • get_by_placeholder;
  • get_by_text;
  • get_by_title.

Uniqueness

A selector matching exactly one element receives a positive adjustment.

Selectors matching no element or several elements are penalized and receive warnings.

Visibility

The first matching element is checked for visibility.

A visible match improves confidence. A hidden match reduces it.

Stability

The stability analyzer detects several potentially fragile patterns, including:

  • dynamically generated IDs;
  • UUID-like IDs;
  • long hexadecimal identifiers;
  • framework-generated classes;
  • overly broad HTML-tag selectors;
  • reused CSS classes.

The final value is normalized to a confidence score between 0 and 100.


Supported contexts

Context Support
Main document โœ…
Single iframe โœ…
Nested iframes โœ…
Open Shadow DOM โœ…
iframe and Shadow DOM combination โœ…

Main document

page.get_by_role(
    "button",
    name="Login",
)

iframe

page.frame_locator(
    "#login-frame"
).get_by_role(
    "button",
    name="Login",
)

Nested iframes

page.frame_locator(
    "#outer-frame"
).frame_locator(
    "#inner-frame"
).get_by_role(
    "button",
    name="Login",
)

Shadow DOM

Playwright automatically traverses open Shadow DOM roots when locators are used.

page.locator(
    "user-panel"
).get_by_role(
    "button",
    name="Login",
)

Traditional approach compared with Playwright Inspector

Traditional approach Playwright Inspector
Manual locator selection Ranked recommendations
Trial and error Measured analysis
Personal preference Objective criteria
CSS-first habits Accessibility-first strategies
One locator without context Complete DOM path
Limited diagnostics Strengths, warnings and confidence
Manual comparison Automatic ranking

Design principles

Accessibility first

User-facing Playwright locators are preferred over implementation-dependent CSS selectors whenever the inspected element provides suitable accessibility information.

Measurable recommendations

Recommendations are not based only on arbitrary preferences. They are evaluated against the current page.

Stability over convenience

A locator should remain understandable and reliable as the application evolves.

One responsibility per component

The architecture separates element inspection, accessibility analysis, DOM traversal, selector generation and selector evaluation.

Developer control

Playwright Inspector recommends. The developer keeps the final decision.


Running the tests

Install the development dependencies:

python -m pip install -e ".[dev]"

Install Chromium:

python -m playwright install chromium

Run the complete suite:

python -m pytest -v

Current validated result:

54 passed
0 failed

Project structure

playwright-inspector/
โ”‚
โ”œโ”€โ”€ assets/
โ”œโ”€โ”€ docs/
โ”œโ”€โ”€ examples/
โ”œโ”€โ”€ playwright_inspector/
โ”‚   โ”œโ”€โ”€ analysis/
โ”‚   โ”œโ”€โ”€ core/
โ”‚   โ”œโ”€โ”€ models/
โ”‚   โ”œโ”€โ”€ resources/
โ”‚   โ””โ”€โ”€ rules/
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ integration/
โ”‚   โ”œโ”€โ”€ playground/
โ”‚   โ””โ”€โ”€ unit/
โ”œโ”€โ”€ LICENSE
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ README.fr.md
โ””โ”€โ”€ pyproject.toml

Roadmap

Version 1.0

  • Public Inspector API;
  • structured InspectionResult;
  • selector generation;
  • selector ranking;
  • accessibility analysis;
  • uniqueness analysis;
  • visibility analysis;
  • stability analysis;
  • iframe support;
  • nested iframe support;
  • open Shadow DOM support;
  • automated test suite;
  • modern Python packaging.

Future development will be guided by real usage and user feedback after the first public release.


Contributing

Contributions, bug reports and constructive suggestions are welcome.

Before submitting a contribution:

  1. create a dedicated branch;
  2. keep the change focused;
  3. add or update tests when behavior changes;
  4. run the complete test suite;
  5. explain the purpose of the change clearly.

Detailed contribution guidelines will be available in CONTRIBUTING.md.


Security

Please do not disclose security-sensitive issues publicly.

Follow the instructions in SECURITY.md to report a potential vulnerability privately.


License

Playwright Inspector is distributed under the MIT License.

See LICENSE for the complete terms.


Author

Christian

Independent Python developer interested in browser automation, testing tools and maintainable software architecture.

Playwright Inspector is the first public release in a broader collection of carefully designed software projects.


Acknowledgements

Playwright Inspector is built with:

  • Python;
  • Playwright;
  • pytest;
  • modern Python packaging tools.

Playwright is a Microsoft project. Playwright Inspector is an independent project and is not affiliated with or endorsed by Microsoft.


Inspect smarter. Test better.

Inspect โ€ข Analyze โ€ข Recommend

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

playwright_inspector-1.0.0.tar.gz (33.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

playwright_inspector-1.0.0-py3-none-any.whl (46.1 kB view details)

Uploaded Python 3

File details

Details for the file playwright_inspector-1.0.0.tar.gz.

File metadata

  • Download URL: playwright_inspector-1.0.0.tar.gz
  • Upload date:
  • Size: 33.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.6

File hashes

Hashes for playwright_inspector-1.0.0.tar.gz
Algorithm Hash digest
SHA256 824ddc8ce3dbb43a9c64624b55170754f5d78d9aff7924d583f2392f03c58c7c
MD5 16b3cc4678d728b37306d9f8b18ad772
BLAKE2b-256 1df4c82f8ad1ff5e30dec36688bfa9f125e8ac39a495d6652fa172eed14448f3

See more details on using hashes here.

File details

Details for the file playwright_inspector-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for playwright_inspector-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f2946f55922a20ec4639d798d185847a7b4de656cf3256004741ccf19dab050f
MD5 0840557a3bc0f0211d6f0c4e35131d00
BLAKE2b-256 2d77c40ace29ce5dfae308a29f1944e1953fe9e8340a140739854bb813fdf9bb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page