使用c#在html文档中动态抓取JavaScript生成的数据

Scraping data dynamically generated by JavaScript in html document using C#

本文关键字:JavaScript 数据 抓取 动态 html 文档 使用      更新时间:2023-09-26

如何使用c#在html文档中抓取JavaScript动态生成的数据?

在c#库中使用WebRequestHttpWebResponse,我能够将整个html源代码作为字符串,但困难的是我想要的数据不包含在源代码中;数据是由JavaScript动态生成的。

另一方面,如果我想要的数据已经在源代码中,那么我可以使用正则表达式轻松地获得它们。

我已经下载了HtmlAgilityPack,但我不知道它是否会照顾的情况下,项目是由JavaScript动态生成的…

非常感谢!

当你做WebRequest时,你要求服务器给你页面文件,这个文件的内容还没有被web浏览器解析/执行,所以上面的javascript还没有做任何事情。

如果您想看到被浏览器解析后的页面是什么样子,则需要使用工具在页面上执行JavaScript。你有一个选择是使用内置的。net浏览器控件:http://msdn.microsoft.com/en-au/library/aa752040(v=vs.85).aspx

web浏览器控件可以导航到并加载页面,然后您可以查询它的DOM,这将被页面上的JavaScript更改。

编辑(示例):

Uri uri = new Uri("http://www.somewebsite.com/somepage.htm");
webBrowserControl.AllowNavigation = true;
// optional but I use this because it stops javascript errors breaking your scraper
webBrowserControl.ScriptErrorsSuppressed = true;
// you want to start scraping after the document is finished loading so do it in the function you pass to this handler
webBrowserControl.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowserControl_DocumentCompleted);
webBrowserControl.Navigate(uri);

private void webBrowserControl_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    HtmlElementCollection divs = webBrowserControl.Document.GetElementsByTagName("div");
    foreach (HtmlElement div in divs)
    {
        //do something
    }
}

您可以使用Selenium之类的工具来抓取包含Javascript的页面。

http://www.andykelk.net/tech/headless-browser-testing-with-phantomjs-selenium-webdriver-c-nunit-and-mono