Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...