Metadata-Version: 2.4
Name: playwright-inspector
Version: 1.0.0
Summary: Analyze DOM elements and generate ranked Playwright selector recommendations.
Author: Christian
License-Expression: MIT
Project-URL: Homepage, https://github.com/CHRISSSSS225/playwright-inspector
Project-URL: Repository, https://github.com/CHRISSSSS225/playwright-inspector
Project-URL: Issues, https://github.com/CHRISSSSS225/playwright-inspector/issues
Project-URL: Changelog, https://github.com/CHRISSSSS225/playwright-inspector/blob/main/CHANGELOG.md
Keywords: playwright,testing,automation,selectors,dom,accessibility
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: playwright<2,>=1.61
Provides-Extra: dev
Requires-Dist: pytest<10,>=9; extra == "dev"
Dynamic: license-file

<p align="center">
  <img src="assets/banner.svg" alt="Playwright Inspector">
</p>

<h1 align="center">Playwright Inspector</h1>

<p align="center">
  <strong>Intelligent Selector Recommendation Engine for Playwright</strong>
</p>

<p align="center">
  <strong>Inspect • Analyze • Recommend</strong>
</p>

<p align="center">

  <a href="https://www.python.org/">
    <img alt="Python 3.11+" src="https://img.shields.io/badge/Python-3.11%2B-blue">
  </a>

  <a href="https://playwright.dev/">
    <img alt="Playwright 1.61+" src="https://img.shields.io/badge/Playwright-1.61%2B-green">
  </a>

  <img alt="Tests" src="https://img.shields.io/badge/Tests-54%20PASS-success">

  <a href="LICENSE">
    <img alt="License MIT" src="https://img.shields.io/badge/License-MIT-orange">
  </a>

  <img alt="Version 1.0.0" src="https://img.shields.io/badge/Version-v1.0.0-blueviolet">

</p>

<p align="center">
  🇬🇧 <strong>English</strong>
  ·
  🇫🇷 <a href="README.fr.md">Français</a>
</p>

---

## 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:

```python
page.get_by_role(...)
```

or:

```python
page.get_by_label(...)
```

or:

```python
page.get_by_placeholder(...)
```

or:

```python
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:

```html
<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:

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

Install the project:

```bash
python -m pip install -e .
```

For development, install the optional test dependencies:

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

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

```bash
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

```python
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:

```text
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.

```python
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.

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

It also supports iteration:

```python
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.

```python
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:

```python
candidate.stars
candidate.confidence
candidate.uniqueness_status
candidate.visibility_status
candidate.stability_status
```

---

## How it works

The public `Inspector` coordinates the complete inspection workflow.

```text
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

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

### iframe

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

### Nested iframes

```python
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.

```python
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:

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

Install Chromium:

```bash
python -m playwright install chromium
```

Run the complete suite:

```bash
python -m pytest -v
```

Current validated result:

```text
54 passed
0 failed
```

---

## Project structure

```text
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

* [x] Public `Inspector` API;
* [x] structured `InspectionResult`;
* [x] selector generation;
* [x] selector ranking;
* [x] accessibility analysis;
* [x] uniqueness analysis;
* [x] visibility analysis;
* [x] stability analysis;
* [x] iframe support;
* [x] nested iframe support;
* [x] open Shadow DOM support;
* [x] automated test suite;
* [x] 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](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.

---

<p align="center">
  <strong>Inspect smarter. Test better.</strong>
</p>

<p align="center">
  Inspect • Analyze • Recommend
</p>
