简体   繁体   English

在C#中使用Selenium IE驱动程序来快速发布大量文本(10,000行)

[英]Using Selenium IE driver in C# to quickly post a large amount of text (10,000 lines)

So I'm currently writing this script that will automate a simple, monotonous task using the Selenium Internet Explorer driver in C#. 因此,我目前正在编写此脚本,该脚本将使用C#中的Selenium Internet Explorer驱动程序自动执行简单,单调的任务。

Everything works great, but it is a tad bit slow at one point in the script and I'm wondering if there is a quicker way available to do what I want. 一切工作都很好,但是脚本中的一点有点慢,我想知道是否有更快的方法可以完成我想要的事情。

The point in question is when I have to fill out a textbox with a lot of information. 问题是当我必须在文本框中填写很多信息时。 This textbox will be filled sometimes up to 10,000 lines where each line never exceeds 20 characters. 有时,此文本框将被填充多达10,000行,每行不得超过20个字符。

However, the following approach is very slow... 但是,以下方法非常慢...

// process sample file using LINQ query
var items = File.ReadAllLines(sampleFile).Select(a => a.Split(',').First());

// Process the items to be what we want to add to the textbox
var stringBuilder = new StringBuilder();
foreach (var item in items)
{
     stringBuilder.Append(item + Environment.NewLine);
}

inputTextBox.SendKeys(stringBuilder.ToString());

Is there any to just set the value of the textbox to what I want? 有什么可以将文本框的值设置为我想要的吗? Or is this a bottleneck? 还是这是一个瓶颈?

Thank you for your time and patience! 感谢您的时间和耐心!

So as suggested by Richard - I ended up using IJavaScriptExecutor . 因此,正如理查德(Richard)建议的那样,我最终使用了IJavaScriptExecutor

The exact solution was to replace the call to SendKeys in the following line of code: 确切的解决方案是在以下代码行中替换对SendKeys的调用:

inputTextBox.SendKeys(stringBuilder.ToString());

With this line of code: 使用以下代码行:

((IJavaScriptExecutor)ieDriver).ExecuteScript("arguments[0].value = arguments[1]",
                                          inputTextBox, stringBuilder.ToString());

Casting my InternetExplorerDriver object to the IJavaScriptExecutor interface in order to reach the explicitly implemented interface member ExecuteScript and then making the call to that member with the arguments above did the trick. 将我的InternetExplorerDriver对象IJavaScriptExecutor转换为IJavaScriptExecutor接口,以到达显式实现的接口成员ExecuteScript ,然后使用上面的参数对该成员进行调用就达到了目的。

To avoid using SendKeys, you could use IJavaScriptExecutor to set the value directly. 为了避免使用SendKeys,可以使用IJavaScriptExecutor直接设置值。 Something along these lines: 遵循以下原则:

string javascript = "document.getElementById("bla").value = stringBuilder";
IJavaScriptExecutor js = (IJavaScriptExecutor)Driver;
js.ExecuteScript(javascript);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM