webBrowser_DocumentCompleted 触发但页面未加载

问题描述

我正在尝试使用 C# 和 HTMLAgilityPAck 来做一个简单的网络爬虫来检查 ServiceNow 页面,但我遇到了一些问题(该站点使用了一个 js 脚本来创建我要抓取的页面的 HTML)。

首先:无论我做什么,当 DocumentCompleted 被触发时,页面似乎并没有完全加载。调试我发现页面doc = webbrowser.Document 的 4 次迭代后加载,所以我只是开始使用 for 循环,但我想要一个更干净的东西(已经尝试过循环ReadyState 但它也不起作用)...

第二件事:当代码实际获取页面时,我似乎无法从中提取元素(并且代码永远不会退出 while 循环)...

这是代码

public partial class Dashboard : Form
{
    String comm = "";
    Uri uri = null;
    Thread thread = null;
    bool logged = false;

    public Dashboard()
    {
        InitializeComponent();
    }

    private void checkTasks()
    {
        if (comm.Equals("g1"))
        {
            uri = new Uri("g1URL");
        }
        else if (comm.Equals("p1"))
        {
            uri = new Uri("p1URL");
        }
        
        Invoke(new Action(() =>
        {
            results.Links.Clear();
            webbrowser1.AllowNavigation = true;
            webbrowser1.ScriptErroRSSuppressed = true;

        }));

        webbrowser1.Navigate(uri);
    }

    private void webbrowser1_DocumentCompleted(object sender,WebbrowserDocumentCompletedEventArgs e)
    {
       
        HtmlDocument doc = null;
        HtmlElement name,pass,submit = null;
        bool proceed = false;

        for (int i = 0; i < 4; i++)
        {
            doc = webbrowser1.Document;
        }

        if (!logged)
        {
            while (!proceed)
            {
                name = doc.GetElementById("userNameInput");
                pass = doc.GetElementById("passwordInput");
                submit = doc.GetElementById("submitButton");
                if (name != null)
                {
                    name.SetAttribute("value","usernameValue");
                    pass.SetAttribute("value","passValue");
                    submit.InvokeMember("click");
                    logged = true;
                    proceed = true;
                }
            }
        }

        webbrowser1.Navigate(uri);
        HtmlElementCollection trs = doc.GetElementsByTagName("tr");
        if (trs.Count != 0)
        {
            foreach (HtmlElement tr in trs)
            {
                results.Text = "NEW TASKS OPENED";
                results.Links.Add(0,16,uri);
            }
        }
        else
        {
            results.Text = "NO NEW TASKS";
        }
    }

    private void g1_Click(object sender,EventArgs e)
    {
        comm = "g1";
        thread = new Thread(checkTasks);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
    }

    private void p1_Click(object sender,EventArgs e)
    {
        comm = "p1";
        thread = new Thread(checkTasks);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
    }
}

有什么想法吗?!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)