Selenium获取Blazor页面邮箱文本框输入值返回Null如何解决
问题原因
- Selenium的
GetAttribute方法对参数大小写敏感,你代码中使用的"Value"首字母大写不符合HTML标准中输入框值属性的小写命名规范,会导致读取失败。 - 你测试的站点基于Blazor开发,其双向绑定逻辑默认不会实时将用户输入值同步到DOM的Attribute上,直接读取Attribute可能无法拿到最新的输入内容,需要读取DOM元素的Property才能获取实时值。
解决方案
方案1:修正属性名(简单场景可用)
将原代码中读取属性的参数改为小写value即可:
string checkText = Field.GetAttribute("value");
方案2:通过JS执行器读取(兼容性最强,推荐适配Blazor场景)
直接调用浏览器JS接口读取输入框DOM的value Property,不受前端框架绑定逻辑影响,稳定性最高,修改后的完整代码如下:
public static void SendKeysElement(IWebDriver webDriver) { IWebElement Field = webDriver.FindElement(By.XPath(selector)); Field.SendKeys("example@example.com"); IJavaScriptExecutor js = (IJavaScriptExecutor)webDriver; string checkText = (string)js.ExecuteScript("return arguments[0].value;", Field); if (checkText != "example@example.com") { Console.WriteLine("String is wrong"); } else { Console.WriteLine("String is correct"); } }
可选优化:添加显式等待
如果Blazor页面存在异步渲染延迟,可以添加最多1秒的显式等待,避免校验时输入值还未更新导致的误判:
WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(1)); wait.Until(d => Field.GetAttribute("value") == "example@example.com");
内容的提问来源于stack exchange,提问作者Beardy
相关产品推荐
相关产品推荐

