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

使用Selenium C#无法在Angular自动搜索字段中输入值

解决Angular Material自动完成输入框的自动化填充问题

你遇到的是Angular Material自动完成组件(mat-autocomplete)的常见自动化问题——这类组件依赖Angular的表单变更检测和特定事件触发,普通的DOM操作不会同步到Angular内部状态,导致输入后无法触发搜索或下拉列表展示。

先修正你现有代码的明显问题

你的第一个Actions代码缺少调用.Perform(),导致动作没有实际执行:

// 修正后的Actions方法
Actions action = new Actions(driver);
action.MoveToElement(LocatorofElement)
       .Click() // 先确保元素被聚焦
       .SendKeys("Value")
       .Perform(); // 必须调用Perform才会执行动作

针对Angular Material Autocomplete的有效解决方案

方案1:触发完整的DOM事件序列

Angular组件需要监听input或change事件来更新内部状态,单纯设置value不会触发这些事件。用JavaScript执行以下步骤:

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// 1. 设置输入框值
js.ExecuteScript("arguments[0].value = arguments[1];", LocatorofElement, "Value");
// 2. 触发input事件,通知Angular值已变更
js.ExecuteScript(@"
    var event = new Event('input', { bubbles: true });
    arguments[0].dispatchEvent(event);
", LocatorofElement);
// 3. 可选:触发change事件确保表单验证同步
js.ExecuteScript(@"
    var event = new Event('change', { bubbles: true });
    arguments[0].dispatchEvent(event);
", LocatorofElement);

方案2:使用Selenium的SendKeys并确保元素可交互

先通过显式等待确保元素处于可交互状态,再调用SendKeys:

using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium;

// 显式等待元素可交互(等待10秒)
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement autoCompleteInput = wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("mat-input-58")));

// 先清空输入框(避免原有内容干扰)
autoCompleteInput.Clear();
// 输入值
autoCompleteInput.SendKeys("Value");
// 可选:按回车键触发搜索(如果组件支持)
autoCompleteInput.SendKeys(Keys.Enter);

方案3:直接操作Angular的FormControl(进阶)

如果能定位到组件对应的Angular FormControl,可以直接设置其值,这是最可靠的方式:

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// 获取Angular组件实例并设置FormControl值
js.ExecuteScript(@"
    // 获取输入框对应的Angular组件实例
    const component = ng.getComponent(arguments[0]);
    // 设置FormControl的值
    component.ngControl.control.setValue(arguments[1]);
", LocatorofElement, "Value");

注意:此方法需要页面加载了Angular的调试模式(ng.getComponent可用),生产环境可能被禁用。

关键注意事项

  • 避免直接设置DOM value:Angular的表单状态和DOM绑定,直接改DOM不会同步到组件内部状态。
  • 确保事件冒泡:触发事件时必须设置bubbles: true,这样事件才能被Angular的监听机制捕获。
  • 显式等待:Angular页面加载可能有延迟,必须等待元素可交互后再操作,避免因元素未就绪导致的失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:20:10