使用C#运行Phantomjs以获取网页快照

我正在尝试使用phantomjs抓取我自己网站的快照 – 基本上,这是创建用户提交内容的“预览图像”。

我在服务器上安装了phantomjs并确认从命令行运行它对适当的页面工作正常。 但是,当我尝试从网站上运行它时,似乎没有做任何事情。 我已经确认正在调用代码,幻像实际上正在运行(我监视过程,并且当我调用它时可以看到它出现在进程列表中) – 但是,没有生成图像。

我不知道我应该在哪里找出为什么它不会创建图像 – 任何建议? 相关代码块如下:

string arguments = "/c rasterize.js http://www.mysite.com/viewcontent.aspx?id=123"; string imagefilename = @"C:\inetpub\vhosts\mysite.com\httpdocs\Uploads\img123.png"; Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = false; p.StartInfo.FileName = @"C:\phantomjs.exe"; p.StartInfo.Arguments = arguments + " " + imagefilename; p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); 

我检查了phantomjs在其过程中抛出的错误。 您可以从Process.StandardError中读取它们。

 var startInfo = new ProcessStartInfo(); //some other parameters here ... startInfo.RedirectStandardError = true; var p = new Process(); p.StartInfo = startInfo; p.Start(); p.WaitForExit(timeToExit); //Read the Error: string error = p.StandardError.ReadToEnd(); 

它会让你知道发生了什么

从C#代码执行phantomjs的最简单方法是使用像NReco.PhantomJS这样的包装器。 以下示例说明了如何将其用于rasterize.js:

 var phantomJS = new PhantomJS(); phantomJS.Run( "rasterize.js", new[] { "https://www.google.com", outFile} ); 

Wrapper API具有stdout和stderr的事件; 它也可以提供来自C#Stream的输入并将stdout结果读入C#流。