C#下载HTML字符串在页面加载完成后

3

我正在尝试使用循环下载一些HTML页面并提取内部数据。但是这些页面在加载时会运行一些JavaScript任务。因此,我认为使用WebClient可能不是一个好选择。但是如果我像下面这样使用WebBrowser,则在循环的第一次调用后返回空的HTML字符串。

WebBrowser wb = new WebBrowser();
        wb.ScrollBarsEnabled = false;
        wb.ScriptErrorsSuppressed = true;
        wb.Navigate(url);
        while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); Thread.Sleep(1000); }
        html = wb.Document.DomDocument.ToString();

如果使用WebClient的DownloadString方法会有帮助吗? - User2012384
1个回答

5
您说得对,WebClient和所有其他HTTP客户端界面都会完全忽略JavaScript;毕竟它们都不是浏览器。
您想要:
var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;

请注意,如果您通过WebBrowser加载,就不需要抓取原始标记;您可以使用DOM方法,例如GetElementById/TagName等等。
while循环非常VBScript,您应该将代码与DocumentCompleted事件连接起来。
private void Whatever()
{
    WebBrowser wb = new WebBrowser();
    wb.DocumentCompleted += Wb_DocumentCompleted;

    wb.ScriptErrorsSuppressed = true;
    wb.Navigate("http://stackoverflow.com");
}

private void Wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    var wb = (WebBrowser)sender;

    var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;
    var domd = wb.Document.GetElementById("copyright").InnerText;
    /* ... */
}

非常感谢Alex。这正是我要找的答案。您能向我展示如何添加DocumentCompleted事件吗? - Mike Long
编辑并附上示例。 - Alex K.
Alex,谢谢。这是一个控制台应用程序。我使用了这段代码,但没有触发Wb_DocumentCompleted函数。 - Mike Long
1
哦。请参阅线程评论:在控制台应用程序中使用WebBrowser - Alex K.
Alex,非常感谢你,你救了我的一天。 - Mike Long
我遇到了“无法实例化ActiveX控件'8856f961-340a-11d0-a96b-00c04fd705a2',因为当前线程不在单线程公寓中”的错误。你能帮忙吗? - Arya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接