我有一个 Web 浏览器和 Visual Studio
中的一个标签,基本上我想做的是从另一个网页中抓取一个部分。
我尝试使用 WebClient.DownloadString
和 WebClient.DownloadFile
,它们都在 JavaScript 加载内容之前为我提供了网页的源代码。我的下一个想法是使用网络浏览器工具,并在页面加载后调用 webBrowser.DocumentText
,但这没有用,它仍然为我提供了页面的原始来源。
有没有办法在 JavaScript
加载后抓取页面?
最佳答案
问题是浏览器通常会执行 javascript 并导致更新的 DOM。除非您可以分析 javascript 或拦截它使用的数据,否则您将需要像浏览器一样执行代码。过去我遇到过同样的问题,我使用 selenium 和 PhantomJS 来渲染页面。呈现页面后,我将使用 WebDriver 客户端导航 DOM 并检索我需要的内容,发布 AJAX。
概括地说,这些是步骤:
- 已安装 Selenium :http://docs.seleniumhq.org/
- 将 selenium hub 作为一项服务启动
- 已下载 phantomjs( headless 浏览器,可以执行 javascript):http://phantomjs.org/
- 在指向 selenium hub 的 webdriver 模式下启动 phantomjs
- 在我的抓取应用程序中安装了 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/projects/webdriver/
编辑:更简单的方法
似乎有一个 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/