如何使用Selenium获取ql-editor富文本编辑器中的文本值
问题原因
ql-editor是Quill富文本编辑器的编辑区域容器,属于可编辑的普通DOM元素(div/p标签),而非<input>、<textarea>这类原生表单输入控件,本身不存在value属性,因此调用GetAttribute("value")只能获取到Null。
修复方案
- 将获取属性的逻辑替换为取普通元素的文本内容即可,三种写法效果一致:
- 直接取元素的
Text属性:string checkText = Field.Text; - 取
textContent属性:string checkText = Field.GetAttribute("textContent"); - 取
innerText属性:string checkText = Field.GetAttribute("innerText");
- 直接取元素的
- 可选优化项:
- 替换强制等待
Thread.Sleep为Selenium显式等待,降低执行耗时、避免网络波动导致的判断错误 - 将
maxTries作为方法参数传递,避免全局变量复用带来的计数异常
- 替换强制等待
修复后示例代码
public static void SendKeysElement(IWebDriver webDriver, string statusMessage, int maxTries = 3) { // 优先定位富文本编辑容器,再操作子p标签稳定性更高 IWebElement editor = webDriver.FindElement(By.XPath("//div[@class='ql-editor']")); IWebElement field = editor.FindElement(By.XPath("./p")); field.SendKeys("Do this and this"); // 替换为显式等待文本加载 WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(2)); wait.Until(d => field.Text.Trim() == "Do this and this"); string checkText = field.Text; if (maxTries < 0) { throw new Exception("String not found"); } else if (checkText != "Do this and this") { maxTries--; SendKeysElement(webDriver, statusMessage, maxTries); } Console.WriteLine(statusMessage); }
内容的提问来源于stack exchange,提问作者Beardy
相关产品推荐
相关产品推荐

