Using Selenium IE driver in C# to quickly post a l

2019-06-10 00:37发布

So I'm currently writing this script that will automate a simple, monotonous task using the Selenium Internet Explorer driver in C#.

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.

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!

2条回答
趁早两清
2楼-- · 2019-06-10 00:57

To avoid using SendKeys, you could use IJavaScriptExecutor to set the value directly. Something along these lines:

string javascript = "document.getElementById("bla").value = stringBuilder";
IJavaScriptExecutor js = (IJavaScriptExecutor)Driver;
js.ExecuteScript(javascript);
查看更多
beautiful°
3楼-- · 2019-06-10 01:07

So as suggested by Richard - I ended up using IJavaScriptExecutor.

The exact solution was to replace the call to SendKeys in the following line of code:

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.

查看更多
登录 后发表回答