I'm doing an automation program. I load a webpage into my windows form and load it in WebBrowser control. Then, I need to click on a link from the WebBrowser programatically. How can I do this? for example:
<a href="http://www.google.com">Google Me</a>
<a href="http://www.facebook.com" id="fbLink">Facebook Me</a>
The above are 2 different conditions. The first element does not have an id
attribute while the second one does. Any idea on how to click each programmatically?
You have to find your element first, by its ID or other filters:
HtmlElement fbLink = webBrowser.Document.GetElementByID("fbLink");
And to simulate "click":
fbLink.InvokeMember("click");
An example for finding your link by inner text:
HtmlElement FindLink(string innerText)
{
foreach (HtmlElement link in webBrowser.Document.GetElementsByTagName("a"))
{
if (link.InnerText.Equals("Google Me"))
{
return link;
}
}
}
You need a way to automate the browser then.
One way to do this is to use Watin (https://sourceforge.net/projects/watin/). It allows you to write a .Net program that controls the browser via a convenient object model. It is mainly used to write automated tests for web pages, but it can also be used to control the browser.
If you don't want to control the browser this way then you could write a javascript that you include on your page that does the clicking, but I doubt that is what you are after.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With