You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Dictionary<string, IWebElement>取值实现FindElement元素缓存功能

补全后的完整代码
// 修正原拼写错误:IWebElemebnt → IWebElement
Dictionary<string, IWebElement> elementCache = new();

public bool IsEnableElement(UiElement locator)
{
   return locator.IsVisible();
}

public IWebElement FindElement(UiElement locator)
{
    // 生成缓存键:用定位符的唯一标识作为字典key
    var cacheKey = locator.ToString();

    // 优先检查缓存是否存在对应元素
    if (elementCache.ContainsKey(cacheKey))
    {
        // 可选补充:校验缓存元素是否仍有效,失效则删除旧缓存走查找逻辑
        // try { if (elementCache[cacheKey].Enabled) return elementCache[cacheKey]; }
        // catch (StaleElementReferenceException) { elementCache.Remove(cacheKey); }
        
        // 按需求直接返回缓存元素
        return elementCache[cacheKey];
    }

    // 缓存未命中时执行查找逻辑
    var webElement = FindElementInParent(FindParent(locator), locator.By);
    // 存入缓存,用TryAdd避免重复添加异常
    elementCache.TryAdd(cacheKey, webElement);
    return webElement;
}
逻辑说明
  • 以元素定位符的字符串形式作为缓存唯一key,匹配元素定位的唯一性要求
  • 调用时优先查询本地缓存,命中直接返回,大幅降低重复DOM查询的性能消耗
  • 缓存未命中时执行原生查找逻辑,将结果存入缓存后返回,后续调用即可直接命中

可选优化点:可增加缓存元素有效性校验逻辑,页面刷新、DOM变动导致元素失效时,自动删除旧缓存重新查找,避免返回陈旧元素报错。

内容的提问来源于stack exchange,提问作者Vlad Yrch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:24:03