惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
G
Google Developers Blog
有赞技术团队
有赞技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Blog — PlanetScale
Blog — PlanetScale
罗磊的独立博客
博客园 - 聂微东
V
Visual Studio Blog
博客园_首页
D
DataBreaches.Net
腾讯CDC
I
InfoQ
F
Fortinet All Blogs
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
Google DeepMind News
Google DeepMind News
人人都是产品经理
人人都是产品经理
云风的 BLOG
云风的 BLOG
月光博客
月光博客
Recent Announcements
Recent Announcements
MongoDB | Blog
MongoDB | Blog
C
Check Point Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Building Self-Healing Selenium Frameworks with AI
Yash Pandey · 2026-04-26 · via DEV Community

Building Self-Healing Selenium Frameworks with AI


One of the biggest pain points in UI test automation is flaky locators. A developer renames a class, restructures a component, and suddenly 40 tests are failing — not because the feature broke, but because the test couldn't find the element.

Self-healing frameworks solve this. With a bit of AI in the mix, your tests can recover from locator failures at runtime instead of crashing.


What "Self-Healing" Actually Means

A self-healing test framework doesn't just retry. It:

  1. Detects a broken locator at runtime
  2. Uses fallback strategies (or AI ranking) to find the correct element
  3. Optionally updates the locator in source so the same error doesn't repeat

This is different from flaky test retries — you're fixing the root cause, not suppressing the symptom.


The Core Pattern: Locator Fallback Chain

from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

LOCATOR_STRATEGIES = [
    (By.ID, "submit-btn"),
    (By.CSS_SELECTOR, "button[data-testid='submit']"),
    (By.XPATH, "//button[contains(text(),'Submit')]"),
    (By.CSS_SELECTOR, "form button[type='submit']"),
]

def find_element_with_healing(driver):
    for strategy, locator in LOCATOR_STRATEGIES:
        try:
            el = driver.find_element(strategy, locator)
            print(f"Located using: {strategy}{locator}")
            return el
        except NoSuchElementException:
            continue
    raise Exception("Element not found via any strategy")

Enter fullscreen mode Exit fullscreen mode

This is the foundation. Every locator has a priority list. If the primary fails, it cascades.


Adding AI: Ranking Candidates with Similarity Scoring

The smarter version doesn't just fall back blindly — it scores candidates on the page and picks the best match. A simple approach uses DOM attribute similarity:

from difflib import SequenceMatcher

def similarity(a, b):
    return SequenceMatcher(None, a, b).ratio()

def find_best_candidate(driver, target_attributes: dict):
    candidates = driver.find_elements(By.CSS_SELECTOR, "*")
    best_score = 0
    best_element = None

    for el in candidates:
        score = 0
        for attr, value in target_attributes.items():
            el_attr = el.get_attribute(attr) or ""
            score += similarity(el_attr, value)

        if score > best_score:
            best_score = score
            best_element = el

    return best_element if best_score > 0.6 else None

# Usage
element = find_best_candidate(driver, {
    "id": "submit-btn",
    "class": "btn-primary",
    "type": "submit"
})

Enter fullscreen mode Exit fullscreen mode

For production use, replace the similarity scorer with an embedding model (OpenAI, Sentence Transformers) to compare semantic similarity of element context — not just attribute strings.


Closing the Loop: Auto-Updating Locators

The final piece is writing the winning locator back to your test config so future runs use it directly:

import json

def update_locator_store(key, strategy, locator, path="locators.json"):
    with open(path, "r+") as f:
        store = json.load(f)
        store[key] = {"strategy": strategy, "locator": locator}
        f.seek(0)
        json.dump(store, f, indent=2)

Enter fullscreen mode Exit fullscreen mode

Combine this with your CI pipeline to generate a PR or comment when a locator heals — giving your team visibility without manual intervention.


When Not to Use This

Self-healing adds complexity. If your app has a stable design system and disciplined data-testid usage, you probably don't need it. This pattern is most valuable in:

  • Legacy apps with unstable DOM structures
  • Teams where devs and QA are siloed
  • Frequent UI redesigns without test ownership

Tips to Take Further

  • Healenium — open-source proxy that adds self-healing to existing Selenium setups with minimal code change
  • Sentence Transformers — cosine similarity gives better semantic matching than SequenceMatcher
  • Log every healing event to a dashboard — you'll spot design instability patterns quickly

Written by Yash| Senior SDET catching failures other layers miss — cross-validating UI, API, DB simultaneously and test infrastructure.