Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click a link element programmatially with HTMLElement?

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:

  1. <a href="http://www.google.com">Google Me</a>

  2. <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?

like image 425
DEN Avatar asked Mar 15 '11 08:03

DEN


2 Answers

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;
        }
    }
}
like image 184
Saeb Amini Avatar answered Nov 01 '22 10:11

Saeb Amini


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.

like image 44
Rune Grimstad Avatar answered Nov 01 '22 12:11

Rune Grimstad