我怎么能等到网站完成加载?

时间:2015-12-22 05:33:10

标签: c# .net winforms

我的代码现在

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web.UI;

namespace myweb
{
    public partial class Form1 : Form
    {
        static Page page;

        public Form1()
        {
            InitializeComponent();

            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.Navigate("http://www.tapuz.co.il/forums/forumpage/393/%D7%98%D7%91%D7%A2_%D7%95%D7%9E%D7%96%D7%92_%D7%90%D7%95%D7%95%D7%99%D7%A8/%D7%9E%D7%96%D7%92_%D7%94%D7%90%D7%95%D7%95%D7%99%D7%A8");

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string test "completed";
        }
    }
}

问题是它在自己完成加载的页面之前几次到达DocumentCompleted事件。我在字符串test =“completed”上使用断点;并且在页面完全加载之前它停在那里几次。

我希望它会到达那里并使线字符串test =“completed”;最后只有一次网页满载时。

2 个答案:

答案 0 :(得分:4)

每次加载一帧时,都会触发该事件。

由于多种原因(frame,ajax等),

DocumentComplete可能会被多次触发。同时,对于特定文档,window.onload事件将仅被触发一次。所以,也许你可以在window.onload进行处理。我只是尝试在下面这样做。希望它有所帮助。

private void Form1_Load(object sender, EventArgs e){
bool complete = false;
this.webBrowser1.DocumentCompleted += delegate
{
    if (complete)
        return;
    complete = true;
    // DocumentCompleted is fired before window.onload and body.onload
    this.webBrowser1.Document.Window.AttachEventHandler("onload", delegate
    {
        // Defer this to make sure all possible onload event handlers got fired
        System.Threading.SynchronizationContext.Current.Post(delegate 
        {
            // try webBrowser1.Document.GetElementById("id") here
            MessageBox.Show("window.onload was fired, can access DOM!");
        }, null);
    });
};

this.webBrowser1.Navigate("http://www.example.com");}

答案 1 :(得分:0)

试试这个:

public Form1()
{
   InitializeComponent();

   webBrowser1.ScriptErrorsSuppressed = true;
   webBrowser1.Navigate("http://www.tapuz.co.il/forums/forumpage/393/%D7%98%D7%91%D7%A2_%D7%95%D7%9E%D7%96%D7%92_%D7%90%D7%95%D7%95%D7%99%D7%A8/%D7%9E%D7%96%D7%92_%D7%94%D7%90%D7%95%D7%95%D7%99%D7%A8");
   while(webBrowser1.ReadyState != WebBrowserReadyState.Complete)
   {
        Application.DoEvents();
   }
   MessageBox.Show("Site Loaded");
}