C# how to wait for a webpage to finish loading before continuing

后端 未结 11 1272
暖寄归人
暖寄归人 2020-11-27 03:33

I\'m trying to create a program to clone multiple bugs at a time through the web interface of our defect tracking system. How can I wait before a page is completely loaded

11条回答
  •  眼角桃花
    2020-11-27 03:36

    yuna and bnl code failed in the case below;

    failing example:

    1st one waits for completed.but, 2nd one with the invokemember("submit") didnt . invoke works. but ReadyState.Complete acts like its Completed before its REALLY completed:

    wb.Navigate(url);
    while(wb.ReadyState != WebBrowserReadyState.Complete)
    {
       Application.DoEvents();
    }
    MessageBox.Show("ok this waits Complete");
    
    //navigates to new page
    wb.Document.GetElementById("formId").InvokeMember("submit");
    while(wb.ReadyState != WebBrowserReadyState.Complete)
    {
       Application.DoEvents();
    }
    MessageBox.Show("webBrowser havent navigated  yet. it gave me previous page's html.");  
    var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;
    

    how to fix this unwanted situation:

    usage

        public myForm1 {
    
            myForm1_load() { }
    
            // func to make browser wait is inside the Extended class More tidy.
            WebBrowserEX wbEX = new WebBrowserEX();
    
            button1_click(){
                wbEX.Navigate("site1.com");
                wbEX.waitWebBrowserToComplete(wb);
    
                wbEX.Document.GetElementById("input1").SetAttribute("Value", "hello");
                //submit does navigation
                wbEX.Document.GetElementById("formid").InvokeMember("submit");
                wbEX.waitWebBrowserToComplete(wb);
                // this actually waits for document Compelete. worked for me.
    
                var processedHtml = wbEX.Document.GetElementsByTagName("HTML")[0].OuterHtml;
                var rawHtml = wbEX.DocumentText;
             }
         }
    
    //put this  extended class in your code.
    //(ie right below form class, or seperate cs file doesnt matter)
    public class WebBrowserEX : WebBrowser
    {
       //ctor
       WebBrowserEX()
       {
         //wired aumatically here. we dont need to worry our sweet brain.
         this.DocumentCompleted += (o, e) => { webbrowserDocumentCompleted = true;};
       }
         //instead of checking  readState, get state from DocumentCompleted Event 
         // via bool value
         bool webbrowserDocumentCompleted = false;
         public void waitWebBrowserToComplete()
         {
           while (!webbrowserDocumentCompleted )
           { Application.DoEvents();  }
           webbrowserDocumentCompleted = false;
         }
    
     }
    

提交回复
热议问题