Saturday, October 22, 2011

C# Web Browser Automation

There are tons of approaches to most programming tasks, and web browser automation is no exception.
But, with C# there are some facilities provided to make it a lot easier than you may at first suspect.

The WebBrowser class:
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx

The webbrowser class is basically Microsoft IE embedded in your application, not a bad thing if you need a webbrowser!

Inside the webbrowser class is a "Document" property composed of multiple HtmlElements,
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.htmlelement.aspx

Now, the easiest way to use this to our advantage is to use Google chrome, and right click on the element you want to work with (on the browser page) and select "inspect element".

Many times elements include an "id=" section, which be used like so:

HtmlElement he = WebBrowser.Document.GetElementById("loginbutton");

and these elements can be used to our advantage:

he.InvokeMember("click");
he.InnerText = "Something";

This post is by no means complete but does provide a very simple way to easily get started !