How to click a button on an ASP.NET web page programmatically?

前端 未结 9 1578
梦谈多话
梦谈多话 2021-02-09 09:57

I am trying to figure out how to click a button on a web page programmatically.

Specifically, I have a WinForm with a WebBrowser control. Once it navigates to the targe

9条回答
  •  南笙
    南笙 (楼主)
    2021-02-09 10:46

    Just a possible useful extra where the submit button has not been given an Id - as is frequently the case.

        private HtmlElement GetInputElement(string name, HtmlDocument doc) {
                HtmlElementCollection elems = doc.GetElementsByTagName("input");
    
                foreach (HtmlElement elem in elems)
                {
                    String nameStr = elem.GetAttribute("value");
                    if (!String.IsNullOrEmpty (nameStr) && nameStr.Equals (name))
                    {
                        return elem;
                    }
                }
                return null;
        }
    

    So you can call it like so:

     GetInputElement("Login", webBrowser1.Document).InvokeMember("Click");
    

    It'll raise an exception if the submit input with the value 'Login', but you can break it up if you want to conditionally check before invoking the click.

提交回复
热议问题