Search code examples
c#browserhtmlgetelementbyidinvokemember

Using webbrowser to click on a button in a webpage


so what I need to do is to use this code:

WebBrowser browser = new WebBrowser();
browser.Navigate("www.somthing.com");
browser.Document.GetElementById("ID").InvokeMember("click");

and then i need to find the id of the button in the page and put in my code but my problem is some of the buttons don't have Id's! what should I do then? they only have type and class and some other things but no Id. i realized that some buttons might be java and maybe that's why i can't click on them by the usual way. so do you know what should I do?


Solution

  • You said your button element has a className ,you can get this element with like this:

    public Form1()
            {
                InitializeComponent();
                webBrowser1.Navigate("To your register account url");
            }
            int on = 0;
            private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                foreach (HtmlElement btn in webBrowser1.Document.GetElementsByTagName("button"))
                {
                    if (btn.GetAttribute("className") == "yourclassname")
                    {
                        btn.InvokeMember("Click");
                        break;
                    }
                }
            }