Skip to content

Instantly share code, notes, and snippets.

@Harryyan
Created April 22, 2014 03:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Harryyan/11164321 to your computer and use it in GitHub Desktop.
Save Harryyan/11164321 to your computer and use it in GitHub Desktop.
使用phantomjs实现网页批量截图,网页url可存在txt文件中
// Render Multiple URLs to image
var RenderUrlsToImage, arrayOfUrls, system;
system = require("system");
var fs = require('fs');
/*
Render given urls
@param array of URLs to render
@param callbackPerUrl Function called after finishing each URL, including the last URL
@param callbackFinal Function called after finishing everything
*/
RenderUrlsToImage = function(urls, callbackPerUrl, callbackFinal) {
var getFilename, next, page, retrieve, urlIndex, webpage;
urlIndex = 0;
webpage = require("webpage");
page = null;
getFilename = function() {
return "rendermulti-" + urlIndex + ".png";
};
next = function(status, url, file) {
page.close();
callbackPerUrl(status, url, file);
return retrieve();
};
retrieve = function() {
var url;
if (urls.length > 0) {
url = urls.shift();
urlIndex++;
page = webpage.create();
page.viewportSize = {
width: 800,
height: 600
};
page.settings.userAgent = "Phantom.js bot";
return page.open("http://" + url, function(status) {
var file;
file = getFilename();
if (status === "success") {
return window.setTimeout((function() {
page.render(file);
return next(status, url, file);
}), 200);
} else {
return next(status, url, file);
}
});
} else {
return callbackFinal();
}
};
return retrieve();
};
arrayOfUrls = null;
if (system.args.length > 1) {
arrayOfUrls = Array.prototype.slice.call(system.args, 1);
} else {
filedata = fs.read('test.txt'); // read the file into a single string
// arrdata = filedata.split(/[\r\n]/); // split the string on newline and store in array
// arrayOfUrls = ["www.google.com", "github.com", "www.phantomjs.org"];
arrayOfUrls = filedata.split(/[\r\n]/); // split the string on newline and store in array
}
RenderUrlsToImage(arrayOfUrls, (function(status, url, file) {
if (status !== "success") {
return console.log("无法渲染 '" + url + "'");
} else {
return console.log("正在渲染 '" + url + "' 为 '" + file + "'");
}
}), function() {
return phantom.exit();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment