使用 AI 构建自愈 Selenium 框架
发布: (2026年4月26日 GMT+8 08:23)
4 分钟阅读
原文: Dev.to
Source: Dev.to

“自愈” 实际含义
自愈测试框架不仅仅是重试。它:
- 在运行时检测到失效的定位器
- 使用回退策略(或 AI 排序)来寻找正确的元素
- 可选地在源码中更新定位器,以防同样的错误再次出现
这不同于对不稳定测试的重试——你是在修复根本原因,而不是掩盖症状。
核心模式:定位器回退链
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")
每个定位器都有一个优先级列表。如果主定位失败,它会回退到下一个策略。
添加 AI:使用相似度评分对候选项进行排名
更智能的版本不会盲目回退——它会对页面上的候选元素进行评分,并挑选出最佳匹配。一个简单的方法是使用 DOM 属性相似度:
from difflib import SequenceMatcher
from selenium.webdriver.common.by import By
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"
})
在生产环境中,建议用嵌入模型(如 OpenAI、Sentence Transformers)替换相似度评分器,以比较元素上下文的语义相似度——而不仅仅是属性字符串的相似度。
关闭循环:自动更新定位器
最后一步是将成功的定位器写回到测试配置中,以便后续运行直接使用:
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)
将此代码与 CI 流水线结合,在定位器自动修复时生成 PR 或评论——让团队在无需手动干预的情况下获得可见性。
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
进一步的提示
- Healenium — 开源代理,为现有 Selenium 设置添加自愈功能,几乎无需修改代码
- Sentence Transformers — 余弦相似度在语义匹配上优于
SequenceMatcher - 将每一次自愈事件记录到仪表盘——你可以快速发现设计不稳定的模式