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

使用Selenium+C#调用SendKeys()向输入元素赋值成功率不足的优化咨询

提升Selenium SendKeys()执行成功率至99.99%的优化建议

问题背景

我正在使用Selenium(v4.0.30319)搭配Chrome浏览器,已尝试多种设置以确保SendKeys()每次都能成功执行,以下是当前成功率最高的实现代码,寻求能将成功率提升至99.99%的建议。

现有代码

HTML结构

<lw-text-input _nghost-qxr-c303="" class="ng-star-inserted lwCanvasWrapperComponent" tabindex="17" 
        style="transform: matrix(1, 0, 0, 1, 802.368, 241.776); visibility: visible; transform-origin: 0px 0px;">
        <textarea _ngcontent-qxr-c303="" name="PrimeInputTextArea" pinputtextarea="" lwngmodelcomponent="" tooltipposition="right" tooltipstyleclass="lwErrorTooltip" tooltipevent="focus" appendto="body" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" droppable="" rows="1" cols="6" class="ui-inputtext ui-corner-all ui-state-default ui-widget ng-untouched ng-pristine ng-valid ng-star-inserted" style="visibility: visible; width: 72px; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: normal; font-style: normal; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255);">
        </textarea>
        </lw-text-input>

<lw-text-input _nghost-qtr-c303="" class="ng-star-inserted lwCanvasWrapperComponent" tabindex="6" style="transform: matrix(1, 0, 0, 1, 781.776, 152.568); visibility: visible; transform-origin: 0px 0px;">
    <textarea _ngcontent-qtr-c303="" name="PrimeInputTextArea" pinputtextarea="" lwngmodelcomponent="" tooltipposition="right" tooltipstyleclass="lwErrorTooltip" tooltipevent="focus" appendto="body" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" droppable="" rows="1" cols="8" class="ui-inputtext ui-corner-all ui-state-default ui-widget ng-untouched ng-pristine ng-valid ng-star-inserted" style="visibility: visible; width: 169.92px; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: normal; font-style: normal; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255);">
            </textarea>
            </lw-text-input>

C#实现代码

WebDriverWait wait2 = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myField8 = wait2.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("lw-text-input[style='transform: matrix(1, 0, 0, 1, 802.368, 241.776); visibility: visible; transform-origin: 0px 0px;']")));

if (myField8.Enabled)
{
    SendKeysToElement(myField8, "AA25");
}

public void SendKeysToElement(IWebElement element, string text)
{
    
    string bar = string.Empty;
    foreach (char c in text)
    {
        bar += c;
        System.Threading.Thread.Sleep(200);  // wait for 200ms between each character
    }

    System.Threading.Thread.Sleep(5000);
    element.Click();
    element.SendKeys(bar);

}

核心优化建议

1. 重构元素定位逻辑,抛弃不稳定的style依赖

现有定位完全依赖完整style属性,一旦页面渲染坐标变化(比如窗口缩放、动态布局),定位直接失效。改用实际可输入的textarea元素+稳定属性定位:

// 定位目标textarea:结合父容器tabindex和自身name属性,稳定性拉满
By targetInputLocator = By.CssSelector("lw-text-input[tabindex='17'] textarea[name='PrimeInputTextArea']");

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// 等待textarea可见且可交互,而非父容器
IWebElement inputElement = wait.Until(d => 
{
    var elem = d.FindElement(targetInputLocator);
    return elem.Displayed && elem.Enabled;
});

2. 替换硬等待为智能显式等待

Thread.Sleep是硬等待,无法适配页面加载波动,直接全部替换为WebDriverWait的条件等待:

  • 等待元素就绪
  • 等待输入后文本更新验证

3. 确保输入框聚焦并清空原有内容

输入前先清空输入框,避免残留内容干扰,同时确保焦点正确落在textarea上:

inputElement.Click();
// 选中全部内容并删除(兼容多数框架)
inputElement.SendKeys(Keys.Control + "a");
inputElement.SendKeys(Keys.Delete);
// 部分场景可直接用Clear(),优先选上面的方式
// inputElement.Clear();

4. 优化SendKeys执行逻辑

逐字符输入时,等待元素文本更新验证,确保每个字符都成功输入:

public void SendKeysToElement(IWebElement element, string text, WebDriverWait wait)
{
    // 先聚焦并清空
    element.Click();
    element.SendKeys(Keys.Control + "a");
    element.SendKeys(Keys.Delete);

    foreach (char c in text)
    {
        element.SendKeys(c.ToString());
        // 等待当前字符出现在输入框中,避免丢字符
        wait.Until(d => element.Text.Contains(c.ToString()));
    }
}

5. 启用ChromeDriver稳定性参数

初始化浏览器时添加参数,减少自动化特征干扰:

ChromeOptions options = new ChromeOptions();
options.AddArgument("--disable-blink-features=AutomationControlled"); // 禁用自动化提示
options.AddArgument("--start-maximized"); // 最大化启动
options.AddArgument("--disable-extensions"); // 禁用扩展
options.AddArgument("--disable-gpu"); // 禁用GPU加速,避免渲染异常
options.AddArgument("--disable-popup-blocking"); // 禁用弹窗拦截

IWebDriver driver = new ChromeDriver(options);

6. 添加重试机制兜底

针对极端偶发失败场景,添加重试逻辑:

public bool SendKeysWithRetry(IWebElement element, string text, WebDriverWait wait, int maxRetries = 3)
{
    int retryCount = 0;
    while (retryCount < maxRetries)
    {
        try
        {
            SendKeysToElement(element, text, wait);
            // 验证最终输入结果
            if (element.Text.Trim().Equals(text.Trim()))
            {
                return true;
            }
        }
        catch (Exception)
        {
            // 可添加日志记录
        }
        retryCount++;
        Thread.Sleep(1000); // 重试前短暂等待
    }
    return false;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:21:26