C# How to Click Button automatically via WebBrowse

2019-01-14 02:57发布

The Html code of my click page is :

<input type="submit" id="publishButton-ns" class="ubtn ubtn-block"
 name="publish" tabindex="10" value="Publish Post">

I tried this code for clicking:

webBrowser1.Document.GetElementById("publishButton-ns").InvokeMember("click");

but this not found the button.

5条回答
2楼-- · 2019-01-14 03:42

Are you waiting for the page to load first? You should bind a function in your code to wait for the page to load, them click the button:

static void form1_Load() {
    // ...
    webBrowser1.onDocumentReady += webBrowser_DocumentReady;
}

static void webBrowser1_DocumentReady() {
    webBrowser1.Document.GetElementById("publishButton-ns").InvokeMember("Click");
}
查看更多
老娘就宠你
3楼-- · 2019-01-14 03:42

EDIT: This only applies when runat="server" is set, not applicable in this case but leaving for others just in case, my apologies on missing that in the question.

ASP.Net changes the name of elements it renders based on the structure they are in, you can try the following to get the final name of the element:

webBrowser1.Document.GetElementById("<%=publishButton-ns.ClientID%>").InvokeMember("click");
查看更多
Animai°情兽
4楼-- · 2019-01-14 03:43

You can use jQuery and then do something like this $("#publishButton-ns").click();

http://www.jQuery.com/

查看更多
淡お忘
5楼-- · 2019-01-14 03:44

This may help you.

<input type="submit" value="Submit" />

HtmlElementCollection elc = this.webBrowser1.Document.GetElementsByTagName("input");  
foreach (HtmlElement el in elc)  
{  
   if (el.GetAttribute("type").Equals("submit"))  
   {  
        el.InvokeMember("Click");  
   }  
 }
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-14 03:58

Try a combination of @adam's suggestion and capitalize Click

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    webBrowser1.Document
        .GetElementById("ctl00_main_LoginExpoPlanIt_LoginButton")
        .InvokeMember("Click");
}

Just tested this and it didn't work with "click" but did with "Click" :)

I'm using .net 4

查看更多
登录 后发表回答