2015年11月28日
在C#中调用phantomjs抓取网页
phantomjs是一个基于webkit的服务器端 javascript API,它全面支持web而不需浏览器支持,其快速原生支持各种Web标准: DOM 处理, CSS 选择器, JSON, Canvas, 和 SVG。今天的主题是如何在C#中调用phantomjs。以phantomjs为关键词进行搜索,看到最多的功能应该是网站截图。今天先整理一下phantomjs.exe在cmd中的正确的使用方式,然后再介绍在C#中用phantomjs抓取网页。
1.phantomjs.exe的hello world与网站截图
1.1 在phantomjs.org中可以下载PhantomJS的最新版本,解压后在相应的文件夹中找到phantomjs.exe所在路径。
1.2 在phantomjs.exe所在路径下创建一个新的文件,写入如下代码,将文件命名为hello.js并保存。
1 2 |
console.log('Hello, world!'); phantom.exit(); |
1.3 打开cmd,从cmd中进入phantomjs.exe所在的路径,输入命令:phantomjs hello.js,回车后即可在cmd输出窗口中看到伟大的”Hello world!”。注意,直接点击路径下的phantomjs.exe(也就是phantomjs官网中说的REPL)是无法运行的,一定要使用cmd来输入命令。
1.4 接下来我们开始尝试网站截图。在phantomjs.exe所在路径下创建一个新的文件,写入如下代码,将文件命名为baidu.js并保存。
1 2 3 4 5 |
var page = require('webpage').create(); page.open('http://baidu.com/', function() { page.render('baidu.png'); phantom.exit(); }); |
1.5 打开cmd,从cmd中进入phantomjs.exe所在的路径,输入命令:phantomjs hello.js,回车后即可在相同路径下看到一张名为”baidu.png”的图片。
2.在C#中调用phantomjs
在NuGet中搜索phantomjs,会出现如下图所示的一些内容。其中第一个phantomjs安装完成后,完全不知道该如何下手,也找不到任何关于它的资料。所以我开始将注意力转移至第二个NReco.PhantomJS,2015/8/3日刚刚更新,而且有网站与详细的示例,因此我开始尝试使用NReco.PhantomJS。
新建一个.NET的项目,在项目中通过NuGet安装NReco.PhantomJS,然后运行如下代码,即可体验PhantomJS抓取网页:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NReco.PhantomJS; using System.IO; using System.Web.Script.Serialization; namespace phantomjsConsole { class Program { static void Main(string[] args) { var phantomJS = new PhantomJS(); // write result to stdout Console.WriteLine("Getting content from baidu.com directly to C# code..."); var outFileHtml = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "baidu.html"); if (File.Exists(outFileHtml)) File.Delete(outFileHtml); using (var outFs = new FileStream(outFileHtml, FileMode.OpenOrCreate, FileAccess.Write)) { try { phantomJS.RunScript(@" var system = require('system'); var page = require('webpage').create(); page.open('https://baidu.com/', function() { system.stdout.writeLine(page.content); phantom.exit(); }); ", null, null, outFs); } finally { phantomJS.Abort(); // ensure that phantomjs.exe is stopped } } Console.WriteLine("Result is saved into " + outFileHtml); } } } |
据PhantomJS的官网描述,它能做的事情还有很多很多,我会慢慢尝试并记录尝试心得,欢迎围观。