Hello World with Selenium and C#
I decided to take a look at Selenium as a way to automate the Chrome Browser from .NET. You first need to download three bits of software, the Selenium server, – which you run from the command line, and the Selenium Bindings for c#, both from http://docs.seleniumhq.org/download/. Finally, you have to download the Chrome driver from http://chromedriver.storage.googleapis.com/index.html?path=2.9/
I created a console app, and referenced all the WebDriver DLL (selenium\net35\WebDriver.dll), added the using statements:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
and, then declared a public static IWebDriver object
public static IWebDriver Driver = new ChromeDriver(@”C:\research\selenium\”);
The path, was pointing to my Chrome Driver (Win32)
I then started with a simple command in my Main() method to navigate to a URL:
Driver.Navigate().GoToUrl(“http://www.logitravel.co.uk/”);
After that, I wanted to execute some javascript, to fill in the form, and move to the next page, so I wrote this function:
static object ExecuteJavascript(string javascript)
{
object oResult = null;
var javaScriptExecutor = Driver as IJavaScriptExecutor;
if (javaScriptExecutor != null) oResult = javaScriptExecutor.ExecuteScript(javascript);
return oResult;
}
Then it’s just a matter of writing the chain of Javascript commands to navigate the website, and get the information I want, – everything’s synchronous,
Driver.Navigate().GoToUrl(“http://www.logitravel.co.uk/”);
ExecuteJavascript(“document.getElementById(‘hidOrigenSV’).value=’Paris’;”);
ExecuteJavascript(“document.getElementById(‘hidDestinoSV’).value=’Dublin’;”);
ExecuteJavascript(“document.getElementById(‘origenSV’).value=’Paris’;”);
ExecuteJavascript(“document.getElementById(‘destinoSV’).value=’Dublin’;”);
ExecuteJavascript(“document.getElementById(‘datePickerIda’).value = ‘Sat, 7 June, 2014’;”);
ExecuteJavascript(“document.getElementById(‘datePickerVuelta’).value = ‘Sat, 14 June, 2014’;”);
ExecuteJavascript(“document.getElementById(‘btnFormAereoV2’).click();”);
var cheapestPrice = ExecuteJavascript(“return document.getElementById(‘agr_0’).getAttribute(‘data-value’);”);
Console.WriteLine(“Cheapest price:” + cheapestPrice);
Driver.Close();