Cross_Column

Tuesday, 4 August 2026

Self Healing for Locator in Automation framework



Hello Friends, This post will have Self healing for locators
If functionality has been changed, no doubt , we need to modify our script but if slightly change in locator like span changed to div, div changed to p etc then there are several ways that we can acheive self healing

Self-Healing Locators in Robot Framework (Playwright Python)

Self-Healing Locators in Robot Framework (Playwright & Python)

UI automation tests frequently break due to minor frontend updates—such as an updated CSS class, a changed ID, or an altered DOM hierarchy. Self-healing locators allow your test framework to automatically detect broken selectors at runtime, identify the correct target element, and continue test execution without manual intervention.

What is Self-Healing?

Self-healing in test automation refers to a dynamic mechanism where an automation framework recovers from locator failures automatically.

When a standard locator (e.g., #submit-btn) fails to find an element, a self-healing layer intercepts the failure, analyzes alternative attributes (such as aria-label, inner text, XPath, or relative position), identifies the target element, and updates the locator on the fly.

How Self-Healing Works

The self-healing lifecycle follows a structured 5-step process:

1
Initial Search: The test attempts to locate an element using the primary locator strategy.
2
Failure Interception: If the primary locator fails, the failure handler intercepts the error before throwing an exception.
3
DOM Analysis: The framework captures a snapshot of the current DOM tree.
4
Candidate Matching: Alternative strategies evaluate nearby elements to score candidate matches.
5
Execution & Logging: The test uses the healed locator to complete the action and logs the repair for developer review.

How Self-Healing Can Be Achieved Without External Tools

You can implement a custom self-healing mechanism directly in Robot Framework using custom Python keywords and the Browser Library (built on Playwright).

1. The Strategy: Fallback Selector Hierarchy

Define a list of alternative locators for critical elements. If the primary selector fails, a custom Python keyword tries backup selectors sequentially.

2. Custom Python Keyword Implementation (SelfHealing.py)

from robot.libraries.BuiltIn import BuiltIn

class SelfHealing:
    def __init__(self):
        self._browser = None

    @property
    def browser(self):
        if self._browser is None:
            self._browser = BuiltIn().get_library_instance('Browser')
        return self._browser

    def click_with_self_healing(self, primary_locator: str, *fallback_locators: str):
        """
        Attempts to click using the primary locator. 
        If it fails, iterates through fallbacks until one succeeds.
        """
        all_locators = [primary_locator] + list(fallback_locators)
        
        for locator in all_locators:
            try:
                # Use a short timeout to check fallback viability quickly
                self.browser.wait_for_elements_state(locator, state='visible', timeout='2s')
                self.browser.click(locator)
                
                if locator != primary_locator:
                    BuiltIn().log(
                        f"[SELF-HEALED] Primary locator '{primary_locator}' failed. "
                        f"Successfully healed using fallback: '{locator}'",
                        level='WARN'
                    )
                return
            except Exception:
                continue

        raise Exception(f"Self-healing failed: None of the provided locators succeeded: {all_locators}")

3. Robot Framework Test Suite (test_suite.robot)

*** Settings ***
Library    Browser
Library    SelfHealing.py

*** Test Cases ***
User Login With Self Healing
    New Page    https://example.com/login
    
    # Custom keyword tries #login-button-new, then text="Log In", then //button[@type='submit']
    Click With Self Healing    id=login-button-new    text="Log In"    xpath=//button[@type='submit']

Self-Healing With Tools & AI Libraries

If you prefer an automated solution without maintaining manual fallback lists, you can integrate dedicated self-healing listeners into Robot Framework.

1. robotframework-heal (Listener Approach)

robotframework-heal is a Robot Framework listener that automatically intercepts failures during execution across Browser/Playwright and Selenium. It uses deterministic rules combined with LLMs (such as OpenAI or Claude) to heal broken locators and generate patch files.

Installation

pip install robotframework-heal

Configuration & Usage

*** Settings ***
Library    Browser    timeout=3s
Library    Heal

When running your test suite, provide your LLM API configuration via environment variables:

export HEAL_MODEL="openai/gpt-4o-mini"
export HEAL_API_KEY="your-api-key"

robot -d results tests/

Outcome: If a selector breaks, robotframework-heal analyzes the DOM, repairs the selector dynamically during execution, and writes the repaired code into results/heal/ as a readable git patch.

2. robotframework-selfhealing-agents

Maintained by the MarketSquare community, this package integrates a multi-agent AI framework into Robot Framework to intercept broken locators, generate action logs, and support local LLM backends such as Ollama.

Custom Approach vs. Tool-Based Approach

Feature Custom Python Keyword Tool-Based / AI Listener
Setup Effort Low (standard Python) Medium (API keys & setup)
Execution Speed Extremely Fast Slightly slower on AI triage
Maintenance Manual fallback lists Automated DOM inspection
Cost Free LLM API token costs

Best Practices for Playwright Locators

  • Prioritize User-Facing Attributes: Use Playwright's native role and text selectors (Get Element By Role, Get Element By Text).
  • Use Dedicated Test IDs: Use attributes like data-testid that styling updates won't break.
  • Avoid Brittle Paths: Avoid long relative XPaths like div > div:nth-child(3) > span > button.

No comments:

Post a Comment

Few More

Encapsulation in Python

Encapsulation in Python: A Complete Guide with Examples and Diagrams Encapsul...

Popular Posts