webbrowser控件c#只在下次第一次调用时才能工作

时间:2013-02-13 11:51:09

标签: c# visual-studio-2008

我正在尝试从网站中提取一些数据,但是submitbutton仅在文档完成事件中第一次调用。在加载第一个提交的页面文档后,完成的事件未执行 我的代码是

 private void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser b = sender as WebBrowser;
        string response = "";
        response = b.DocumentText;
        HtmlElement links = b.Document.GetElementById("btn1");
        links.InvokeMember("click");
        checkTrafiicButtonClick = true;
        MessageBox.Show("");
        ***// upto these working and loading second page after that i want to fill data   
           and want to submit but down line is not working and it should be work after    
           loading the page that i submitted how can i do these***

        HtmlElement tfrno = b.Document.GetElementById("TrfNo");
        tfrno.SetAttribute("value", "50012079");
        HtmlElement submitButon = b.Document.GetElementById("submitBttn");
        submitButon.InvokeMember("click");

    }

1 个答案:

答案 0 :(得分:1)

根据您的评论,您的代码将无法按预期运行。第一次单击后,webbroser启动异步页面加载。你应该这样做:

private void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser b = sender as WebBrowser;
     if(b.Url.AbsoluteUri == "mydomain.com/page1.html")
     {
        string response = "";
        response = b.DocumentText;
        HtmlElement links = b.Document.GetElementById("btn1");
        links.InvokeMember("click");
        checkTrafiicButtonClick = true;
        MessageBox.Show("");
        return;
     }
        ***// upto these working and loading second page after that i want to fill data   
           and want to submit but down line is not working and it should be work after    
           loading the page that i submitted how can i do these***
     if(b.Url.AbsoluteUri == "mydomain.com//page2.htm")
     {
        HtmlElement tfrno = b.Document.GetElementById("TrfNo");
        tfrno.SetAttribute("value", "50012079");
        HtmlElement submitButon = b.Document.GetElementById("submitBttn");
        submitButon.InvokeMember("click");
        return;
     }
    }

另请注意,页面的某些部分可以从不同的来源加载,例如在iframe中,因此您必须检查正确的uri