【问题标题】:How do i Screen scrape html page generated by javascript我如何屏幕抓取由javascript生成的html页面
【发布时间】:2014-04-12 17:09:56
【问题描述】:

我如何筛选 scrape 由 javascript 生成的 html 页面? 我试过这样的事情:

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        HtmlWeb hw = new HtmlWeb();
        doc = hw.Load("http://stats.nba.com/scores.html?gameDate=04/11/2014");
        HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@id='scoreboards']");

但这不起作用,因为内容是由 javascript 生成的。 javascript生成html后有没有办法抓取页面? 也许使用敏捷包以外的东西?

【问题讨论】:

  • 如果您想废弃由 javascript 创建的 html,请使用 webbrowser 控件
  • @GujjuDeveloper 你能给我一个例子或链接我吗?:)

标签: c# screen-scraping html-agility-pack


【解决方案1】:

使用 webbrowser 控件获取由 js 或 ajax 加载的内容和元素

private void LoadHtmlWithBrowser(String url)
{
    webBrowser1.ScriptErrorsSuppressed = true;
    webBrowser1.Navigate(url);

    waitTillLoad(this.webBrowser1);

    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    var documentAsIHtmlDocument3 = (mshtml.IHTMLDocument3)webBrowser1.Document.DomDocument; 
    StringReader sr = new StringReader(documentAsIHtmlDocument3.documentElement.outerHTML); 
    doc.Load(sr);
}

private void waitTillLoad(WebBrowser webBrControl)
{
    WebBrowserReadyState loadStatus;
    int waittime = 100000;
    int counter = 0;
    while (true)
    {
        loadStatus = webBrControl.ReadyState;
        Application.DoEvents();
        if ((counter > waittime) || (loadStatus == WebBrowserReadyState.Uninitialized) || (loadStatus == WebBrowserReadyState.Loading) || (loadStatus == WebBrowserReadyState.Interactive))
        {
            break;
        }
        counter++;
    }

    counter = 0;
    while (true)
    {
        loadStatus = webBrControl.ReadyState;
        Application.DoEvents();
        if (loadStatus == WebBrowserReadyState.Complete && webBrControl.IsBusy != true)
        {
            break;
        }
        counter++;
    }
}

【讨论】:

  • 谢谢!我有一些问题,WebBrowser1 在哪里实例化?还有你说的通过ajax或者js加载是什么意思?
【解决方案2】:

您可以使用 webbrowser 对象,该对象是一个 c# 对象,其作用类似于浏览器并运行 javascript 代码,并在收到响应后使用敏捷包对其进行解析。

MSDN - Web Browser

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多