How to click a link element programmatially with H

2019-01-23 14:14发布

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?

2条回答
何必那么认真
2楼-- · 2019-01-23 14:35

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.

查看更多
狗以群分
3楼-- · 2019-01-23 14:40

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;
        }
    }
}
查看更多
登录 后发表回答