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

如何使用Selenium获取ql-editor富文本编辑器中的文本值

问题原因

ql-editor是Quill富文本编辑器的编辑区域容器,属于可编辑的普通DOM元素(div/p标签),而非<input>、<textarea>这类原生表单输入控件,本身不存在value属性,因此调用GetAttribute("value")只能获取到Null。

修复方案
  • 将获取属性的逻辑替换为取普通元素的文本内容即可,三种写法效果一致:
    1. 直接取元素的Text属性:string checkText = Field.Text;
    2. 取textContent属性:string checkText = Field.GetAttribute("textContent");
    3. 取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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:48:02