SendKeys 持续时间过长(C# Selenium geckodriver)

SendKeys lasting too long (C# Selenium geckodriver)

我试图在 C# 中使用 Selenium for Firefox 将键(1000 行的字符串)发送到文本区域,但 Selenium 冻结了一分钟,之后出现错误,但文本显示在文本区域。

这是错误:

The HTTP request to the remote WebDriver server for URL timed out after 60 seconds

它可以是什么?

谢谢,


编辑

String text;
IWebElement textarea;

try
{
    textarea.Clear();
    textarea.SendKeys(text); //Here's where it freezes for 60 seconds.
}
catch(Exception e)
{
    //After those 60 seconds, the aforementioned error appears.
}

//And finally, after another 30 seconds, the text appears written on the textarea.

texttextarea 代表一些正确的真实值(元素存在等)

出现异常是因为驱动在60秒内没有响应,可能是因为SendKeys模拟所有按键的时间超过60秒

要么将您的文本拆分为更小的字符串,然后为每个字符串调用 SendKeys

static IEnumerable<string> ToChunks(string text, int chunkLength) {
    for (int i = 0; i < chunkLength; i += chunkLength)
        yield return text.Substring(i, Math.Min(chunkLength, text.Length - i));
}


foreach (string chunk in ToChunks(text, 256))
    textarea.SendKeys(chunk);

或者模拟用户的文本插入(从剪贴板粘贴或删除)。 Selenium 不直接支持此用例,因此您必须使用脚本注入:

string JS_INSERT_TEXT = @"
    var text = arguments[0];
    var target = window.document.activeElement;

    if (!target || target.tagName !== 'INPUT' && target.tagName !== 'TEXTAREA')
      throw new Error('Expected an <input> or <textarea> as active element');

    window.document.execCommand('inserttext', false, text);
    ";

textarea.Clear();
((IJavaScriptExecutor)driver).ExecuteScript(JS_INSERT_TEXT, text);