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

Selenium+NUnit做C# UI测试登录微软提示浏览器异常如何解决

你遇到的异常提示确认为微软站点的反自动化机制识别到Selenium驱动特征导致。Chromedriver默认启动时会携带多项可被检测的特征字段,包括navigator.webdriver属性标记为true、内置自动化扩展、启动参数包含自动化标识等,微软的身份验证系统会拦截这类非真实用户的访问请求。

你原有代码中添加的启动参数未覆盖反检测配置,重复添加--profile-directory=Default以及无意义的.参数属于无效配置,对绕过检测没有帮助。

可行解决方案

方案1:修改Chrome启动参数绕过检测

这是你之前参考内容中提到的通用方案,属于当前阶段的最优解,修改后的启动配置示例如下:

[OneTimeSetUp]
public void StartChrome()
{
    var options = new ChromeOptions();
    // 核心反检测配置
    options.AddArgument("--disable-blink-features=AutomationControlled");
    options.AddExcludedArgument("enable-automation");
    options.AddAdditionalOption("useAutomationExtension", false);
    // 配置真实用户代理,可替换为你本地Chrome的实际UA
    options.AddArgument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36");
    // 原有有效配置保留
    options.AddArgument("--enable-javascript");
    options.AddArgument("--disable-plugins-discovery");
    // 可选:使用本地已存在的Chrome用户配置(需提前手动登录过微软账号,可跳过输入账号密码步骤,仿真度更高)
    // options.AddArgument(@"user-data-dir=C:\Users\你的系统用户名\AppData\Local\Google\Chrome\User Data");

    webDriver = new ChromeDriver(options);
    webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}

同时建议你将原有代码中的Thread.Sleep替换为显式等待,避免机械的固定间隔被识别,操作示例:

[Test]
public void Login()
{
    var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(10));
    webDriver.Navigate().GoToUrl("https://localhost:xxxxx/");
    wait.Until(d => d.FindElement(By.Id("LoginButton"))).Click();

    var accountInput = wait.Until(d => d.FindElement(By.Id("i0116")));
    accountInput.Clear();
    accountInput.SendKeys("username");
    accountInput.SendKeys(Keys.Enter);

    var pwdInput = wait.Until(d => d.FindElement(By.Id("password")));
    pwdInput.Clear();
    pwdInput.SendKeys("password");
    pwdInput.SendKeys(Keys.Enter);

    wait.Until(d => d.FindElement(By.Id("submitBtn"))).Click();
}

注意如果使用本地用户配置,运行代码前需要关闭所有手动打开的Chrome窗口,避免出现配置文件被占用的报错。

方案2:绕开UI登录(更稳定,推荐企业测试场景使用)

如果你的测试核心是自身业务系统,微软登录仅为前置步骤,可以直接调用微软身份平台的接口获取授权令牌,再将令牌注入到浏览器的Cookie或本地存储中,直接跳过登录UI操作,该方案不会触发反爬拦截,长期稳定性更高。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:24:01