【问题标题】:SendKeys lasting too long (C# Selenium geckodriver)SendKeys 持续时间过长(C# Selenium geckodriver)
【发布时间】:2018-04-03 14:12:43
【问题描述】:

我正在尝试在 C# 中使用 Selenium for Firefox 将密钥(一串 1000 行)发送到 textarea,但 Selenium 冻结了一分钟,之后出现错误,但文本显示在 textarea 上。

这是错误:

对远程 WebDriver 服务器的 URL 的 HTTP 请求超时 60秒后

会是什么?

谢谢,


编辑

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 代表一些真实值,它们是正确的(元素存在等)

【问题讨论】:

  • 您使用的是哪种 Selenium 语言绑定艺术Java / Python / C#?你能用你的代码试验更新问题吗?
  • 是的,我已经更新了问题。

标签: c# selenium firefox geckodriver


【解决方案1】:

出现异常是因为驱动程序在 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);

【讨论】:

  • 这似乎是我的问题的解决方案。我今天不能测试,所以我明天试试。
  • @AsierAzkolain 您也可以使用 C# 内置的 Clipboard 类在不使用 JS 的情况下粘贴/复制文本,我相信这可以更好地模拟用户粘贴文本(因为它实际上是在粘贴文本)
  • @Rescis,是的,在剪贴板中设置文本并调用 Keys.Control + "v" 是一个选项。虽然我倾向于避免使用它,因为它很昂贵,并不总是可靠的,而且它不适用于远程实例或无头。
  • @FlorentB。这些是一些公平的反对意见。我个人对它们并没有太大的问题(我的测试都在进行中,当我开始运行 UI 测试这一事实时,性能损失变成了微优化)。欢迎您随意留下您的答案,我只是想我也会添加一个替代方案。
  • 我决定将我的文本分成两个字符串,它工作正常。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多