如何在C#中使用Selenium等待文本框值变化?
解决Selenium等待JS修改输入框值的问题
你的问题核心是错误获取了输入框的实际值:输入框由JS修改的内容存在value属性里,而非Text属性;另外第一种写法直接比较元素对象和空字符串,逻辑完全错误。
问题分析
- 第一种写法中,
driver.FindElement(By.Id("gbpAmount")).Equals("")是拿元素对象和空字符串对比,永远不成立,导致等待逻辑失效。 - 第二种写法使用
Text属性获取值,但<input>标签的显示值存储在value属性中,Text属性无法正确读取JS设置的输入框内容。
正确的等待实现
基础写法:等待值非空且不等于"0"
var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5)); bool isPopulated = wait.Until(driver => { string inputValue = driver.FindElement(By.Id("gbpAmount")).GetAttribute("value"); return !string.IsNullOrEmpty(inputValue) && inputValue != "0"; });
处理空白字符的写法
如果JS设置的值可能包含首尾空格,可先去除空白再判断:
var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5)); bool isPopulated = wait.Until(driver => { string inputValue = driver.FindElement(By.Id("gbpAmount")).GetAttribute("value").Trim(); return !string.IsNullOrEmpty(inputValue) && inputValue != "0"; });
额外优化建议
如果目标元素存在动态加载的可能,建议先等待元素可见,再判断值的变化:
var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5)); // 先确保元素已加载并可见 wait.Until(ExpectedConditions.ElementIsVisible(By.Id("gbpAmount"))); // 再等待值符合要求 bool isPopulated = wait.Until(driver => { string inputValue = driver.FindElement(By.Id("gbpAmount")).GetAttribute("value").Trim(); return !string.IsNullOrEmpty(inputValue) && inputValue != "0"; });
内容的提问来源于stack exchange,提问作者coolblue2000
相关产品推荐
相关产品推荐

