如何在webbrowser上运行每个方法

时间:2016-09-30 02:34:52

标签: c#

        private void button2_Click(object sender, EventArgs e)
        {
         webBrowser1.Document.GetElementById("login_login_button").InvokeMember("Click"); 
//something that wait about 1 or 2 second before execute next line?               
         webBrowser1.Document.GetElementById("nav_settings_link").InvokeMember("Click"); 
         webBrowser1.Document.GetElementById("language_change2").InvokeMember("Click");                                   

        }

从这段代码中,我尝试了Thread.Sleep();Task Delay();但是它显示为nullException ...(我认为因为它们在网页未完全加载时正在运行)任何人都可以帮助我?

现在,我已经发现我想要的方法是异步方法,以便在它们仍在运行时减慢时间。

    private async void button2_Click(object sender, EventArgs e)
        {             webBrowser1.Document.GetElementById("login_login_button").InvokeMember("Click");await Task.Delay(1000);                      webBrowser1.Document.GetElementById("nav_settings_link").InvokeMember("Click"); 
await Task.Delay(1000);        webBrowser1.Document.GetElementById("language_change2").InvokeMember("Click");  }

1 个答案:

答案 0 :(得分:0)

只是一个例子:

using System.Diagnostics;    


Stopwatch sw = new Stopwatch();
int timeout = 60; // 60 seconds
sw.Start(); // Use Restart for the next element, to reset the time to 0 first.
var element = webBrowser1.Document.GetElementById("login_login_button");
while(element == null && sw.Elapsed.TotalSeconds < timeout)
{
    Thread.Sleep(2000);
    element = webBrowser1.Document.GetElementById("login_login_button");
}
sw.Stop();
if(element!=null)
{
    element.InvokeMember("Click"); 
}
...
// if success, repeat with similar pattern for the next element
// if you still can't find the element, you'd better quit what you are trying to do

说明:

  1. 启用秒表的System.Diagnostics
  2. 超时添加,以便您不会永远等待
  3. 将元素存储到变量
  4. 每2秒检查一次元素
  5. 如果找到,请点击并继续下一步
  6. 如果不是......你可能想要放弃你正在做的事情