c# - 使用 C# 抓取由 JavaScript 生成的网页

标签 c# javascript html visual-studio web-scraping

我有一个 Web 浏览器和 Visual Studio 中的一个标签,基本上我想做的是从另一个网页中抓取一个部分。

我尝试使用 WebClient.DownloadStringWebClient.DownloadFile,它们都在 JavaScript 加载内容之前为我提供了网页的源代码。我的下一个想法是使用网络浏览器工具,并在页面加载后调用 webBrowser.DocumentText,但这没有用,它仍然为我提供了页面的原始来源。

有没有办法在 JavaScript 加载后抓取页面?

最佳答案

问题是浏览器通常会执行 javascript 并导致更新的 DOM。除非您可以分析 javascript 或拦截它使用的数据,否则您将需要像浏览器一样执行代码。过去我遇到过同样的问题,我使用 selenium 和 PhantomJS 来渲染页面。呈现页面后,我将使用 WebDriver 客户端导航 DOM 并检索我需要的内容,发布 AJAX。

概括地说,这些是步骤:

  1. 已安装 Selenium :http://docs.seleniumhq.org/
  2. 将 selenium hub 作为一项服务启动
  3. 已下载 phantomjs( headless 浏览器,可以执行 javascript):http://phantomjs.org/
  4. 在指向 selenium hub 的 webdriver 模式下启动 phantomjs
  5. 在我的抓取应用程序中安装了 webdriver 客户端 nuget 包:Install-Package Selenium.WebDriver

以下是 phantomjs 网络驱动程序的示例用法:

var options = new PhantomJSOptions();
options.AddAdditionalCapability("IsJavaScriptEnabled",true);

var driver = new RemoteWebDriver( new URI(Configuration.SeleniumServerHub),
                    options.ToCapabilities(),
                    TimeSpan.FromSeconds(3)
                  );
driver.Url = "http://www.regulations.gov/#!documentDetail;D=APHIS-2013-0013-0083";
driver.Navigate();
//the driver can now provide you with what you need (it will execute the script)
//get the source of the page
var source = driver.PageSource;
//fully navigate the dom
var pathElement = driver.FindElementById("some-id");

有关 selenium、phantomjs 和 webdriver 的更多信息,请访问以下链接:

http://docs.seleniumhq.org/

http://docs.seleniumhq.org/projects/webdriver/

http://phantomjs.org/

编辑:更简单的方法

似乎有一个 phantomjs 的 nuget 包,这样你就不需要集线器了(我使用集群以这种方式进行大量抓取):

安装网络驱动:

Install-Package Selenium.WebDriver

安装嵌入式exe:

Install-Package phantomjs.exe

更新代码:

var driver = new PhantomJSDriver();
driver.Url = "http://www.regulations.gov/#!documentDetail;D=APHIS-2013-0013-0083";
driver.Navigate();
//the driver can now provide you with what you need (it will execute the script)
//get the source of the page
var source = driver.PageSource;
//fully navigate the dom
var pathElement = driver.FindElementById("some-id");

关于c# - 使用 C# 抓取由 JavaScript 生成的网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24288726/

相关文章:

javascript - 尝试将这个函数理解为值

javascript - 如果检查了所有 radio ,则显示/隐藏 div

html - (HTML/CSS) 如何在父元素中垂直居中网格

jquery - 打开 Accordion 时按下页脚

c# - 有 C# token 计数器吗?

c# - 在代码中使用大量硬编码字符串

c# - 如何让 newtonsoft 将 yes 和 no 反序列化为 bool 值

c# - 插入和更新 mysql 值 C#

javascript - 对于 Fabric.js 中的形状,如何知道某人是否正在调整大小以使其变小或变大

javascript - 发现这个讨厌的代码,我想知道它是做什么的?我应该担心……吗?