问题是浏览器通常会执行 javascript,结果是更新了 DOM。除非您可以分析 javascript 或拦截它使用的数据,否则您将需要像浏览器一样执行代码。过去我遇到过同样的问题,我使用 selenium 和 PhantomJS 来呈现页面。在它呈现页面之后,我将使用 WebDriver 客户端来导航 DOM 并检索我需要的内容,发布 AJAX。
概括地说,这些是步骤:
- 已安装硒:http://docs.seleniumhq.org/
- 将 selenium 集线器作为服务启动
- 下载的phantomjs(无头浏览器,可以执行javascript):http://phantomjs.org/
- 以指向 selenium 集线器的 webdriver 模式启动 phantomjs
- 在我的抓取应用程序中安装了 webdriver 客户端 nuget 包:
Install-Package Selenium.WebDriver
以下是 phantomjs webdriver 的示例用法:
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");