Javascript 如何使用casperjs/phantomjs保存当前网页?
有没有办法用casperjs或phantomjs保存当前网页?Javascript 如何使用casperjs/phantomjs保存当前网页?,javascript,phantomjs,casperjs,Javascript,Phantomjs,Casperjs,有没有办法用casperjs或phantomjs保存当前网页? 我尝试获取html并将其保存到文件中。但是结果文件与当时的屏幕截图有很大不同(使用casper.capture)。有没有办法保存当前网页?没有,我认为没有简单的方法可以做到这一点,因为phantomjs不支持以mht格式呈现页面()。我相信这就是你想要的。 因此,需要做一些工作来实现这一点。我做了类似的事情,但我是以另一种方式做的,我有一个渲染的html代码,通过phantomjs渲染成image/pdf。我必须先清理文件,它对我来
我尝试获取html并将其保存到文件中。但是结果文件与当时的屏幕截图有很大不同(使用
casper.capture
)。有没有办法保存当前网页?没有,我认为没有简单的方法可以做到这一点,因为phantomjs不支持以mht格式呈现页面()。我相信这就是你想要的。
因此,需要做一些工作来实现这一点。我做了类似的事情,但我是以另一种方式做的,我有一个渲染的html代码,通过phantomjs渲染成image/pdf。我必须先清理文件,它对我来说很好
所以,我认为你需要做的是:
- 剥离所有js调用,如
标记或script
属性等onload
- 如果您可以从本地访问css、图像等资源(并且不需要对抓取页面的域进行身份验证),则需要将
属性的相对路径更改为绝对以加载图像/etcsrc
- 如果您在打开页面时无法访问这些资源,那么我认为您需要实现在phantomjs加载页面时下载这些资源,然后将
属性重定向到该文件夹,或者使用数据uri。 您可能还需要更改css文件中的链接src
。/
或/
之类内容的远程资源路径
我使用检索当前页面内容并遍历所有捕获的资源,以将标记中使用的路径(由完整资源URL的一部分标识)替换为随机生成的文件名。文件扩展名是根据资源的内容类型创建的。它是使用
由于CSS文件可能包含背景图像或字体,因此在保存到磁盘之前必须对其进行处理。提供的loadResource
函数加载资源,但不保存资源
由于XMLHttpRequest需要下载资源,因此必须使用--web security=false
标志调用脚本:
casperjs script.js --web-security=false
script.js
var casper = require("casper").create();
var utils = require('utils');
var fs = require('fs');
var mimetype = require('./mimetype'); // URL provided below
var cssResources = [];
var imgResources = [];
var fontResources = [];
var resourceDirectory = "resources";
var debug = false;
fs.removeTree(resourceDirectory);
casper.on("remote.message", function(msg){
this.echo("remote.msg: " + msg);
});
casper.on("resource.error", function(resourceError){
this.echo("res.err: " + JSON.stringify(resourceError));
});
casper.on("page.error", function(pageError){
this.echo("page.err: " + JSON.stringify(pageError));
});
casper.on("downloaded.file", function(targetPath){
if (debug) this.echo("dl.file: " + targetPath);
});
casper.on("resource.received", function(resource){
// don't try to download data:* URI and only use stage == "end"
if (resource.url.indexOf("data:") != 0 && resource.stage == "end") {
if (resource.contentType == "text/css") {
cssResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("image/") == 0) {
imgResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("application/x-font-") == 0) {
fontResources.push({obj: resource, file: false});
}
}
});
// based on http://docs.casperjs.org/en/latest/modules/casper.html#download
casper.loadResource = function loadResource(url, method, data) {
"use strict";
this.checkStarted();
var cu = require('clientutils').create(utils.mergeObjects({}, this.options));
return cu.decode(this.base64encode(url, method, data));
};
function escapeRegExp(string) {
// from https://stackoverflow.com/a/1144788/1816580
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(find, replace, str) {
// from https://stackoverflow.com/a/1144788/1816580
return str.replace(find, replace);
}
var wrapFunctions = [
function wrapQuot1(s){
return '"' + s + '"';
},
function wrapQuot2(s){
return "'" + s + "'";
},
function csswrap(s){
return '(' + s + ')';
}
];
function findAndReplace(doc, resources, resourcesReplacer) {
// change page on the fly
resources.forEach(function(resource){
var url = resource.obj.url;
// don't download again
if (!resource.file) {
// set random filename and download it **or** call further processing which in turn will load ans write to disk
resource.file = resourceDirectory+"/"+Math.random().toString(36).slice(2)+"."+mimetype.ext[resource.obj.contentType];
if (typeof resourcesReplacer != "function") {
if (debug) casper.echo("download resource (" + resource.obj.contentType + "): " + url + " to " + resource.file);
casper.download(url, resource.file, "GET");
} else {
resourcesReplacer(resource);
}
}
wrapFunctions.forEach(function(wrap){
// test the resource url (growing from the back) with a string in the document
var lastURL;
var lastRegExp;
var subURL;
// min length is 4 characters
for(var i = 0; i < url.length-5; i++) {
subURL = url.substring(i);
lastRegExp = new RegExp(escapeRegExp(wrap(subURL)), "g");
if (doc.match(lastRegExp)) {
lastURL = subURL;
break;
}
}
if (lastURL) {
if (debug) casper.echo("replace " + lastURL + " with " + resource.file);
doc = replaceAll(lastRegExp, wrap(resource.file), doc);
}
});
});
return doc;
}
function capturePage(){
// remove all <script> and <base> tags
this.evaluate(function(){
Array.prototype.forEach.call(document.querySelectorAll("script"), function(scr){
scr.parentNode.removeChild(scr);
});
Array.prototype.forEach.call(document.querySelectorAll("base"), function(scr){
scr.parentNode.removeChild(scr);
});
});
// TODO: remove all event handlers in html
var page = this.getHTML();
page = findAndReplace(page, imgResources);
page = findAndReplace(page, cssResources, function(cssResource){
var css = casper.loadResource(cssResource.obj.url, "GET");
css = findAndReplace(css, imgResources);
css = findAndReplace(css, fontResources);
fs.write(cssResource.file, css, "wb");
});
fs.write("page.html", page, "wb");
}
casper.start("http://www.themarysue.com/").wait(3000).then(capturePage).run(function(){
this.echo("DONE");
this.exit();
});
var casper=require(“casper”).create();
var utils=require('utils');
var fs=需要('fs');
var mimetype=require('./mimetype');//下面提供了URL
var cssResources=[];
var imgResources=[];
var fontResources=[];
var resourceDirectory=“resources”;
var-debug=false;
fs.removeTree(资源目录);
casper.on(“remote.message”,函数(msg){
this.echo(“remote.msg:+msg”);
});
casper.on(“resource.error”,函数(resourceError){
this.echo(“res.err:+JSON.stringify(resourceError));
});
casper.on(“page.error”,函数(pageError){
this.echo(“page.err:+JSON.stringify(pageError));
});
casper.on(“下载的.file”,函数(targetPath){
如果(调试)this.echo(“dl.file:+targetPath”);
});
casper.on(“resource.received”,函数(resource){
//不要尝试下载数据:*URI,只使用stage==“end”
if(resource.url.indexOf(“数据:”)!=0&&resource.stage==end){
if(resource.contentType==“text/css”){
push({obj:resource,file:false});
}
if(resource.contentType.indexOf(“image/”)==0){
push({obj:resource,file:false});
}
if(resource.contentType.indexOf(“应用程序/x-font-”)==0){
push({obj:resource,file:false});
}
}
});
//基于http://docs.casperjs.org/en/latest/modules/casper.html#download
casper.loadResource=函数loadResource(url、方法、数据){
“严格使用”;
this.checkStarted();
var cu=require('clientutils').create(utils.mergeObjects({},this.options));
返回cu.decode(此.base64encode(url、方法、数据));
};
函数escapeRegExp(字符串){
//从https://stackoverflow.com/a/1144788/1816580
返回字符串.replace(/([.*+?^=!:${}()\[\]\/\]])/g,“\\$1”);
}
函数replaceAll(查找、替换、str){
//从https://stackoverflow.com/a/1144788/1816580
返回str.replace(查找、替换);
}
变量包装函数=[
功能wrapQuot1(s){
返回“'+s+'”;
},
功能包装UOT2(s){
返回“'”+s+“'”;
},
功能csswrap(s){
返回“(“+s+”)”;
}
];
功能查找和替换(文档、资源、资源替换){
//动态换页
resources.forEach(函数(资源){
var url=resource.obj.url;
//不要再下载了
如果(!resource.file){
//设置随机文件名并下载**或**调用进一步处理,这将依次加载ans写入磁盘
resource.file=resourceDirectory++“/”+Math.random().toString(36.slice(2)+“+mimetype.ext[resource.obj.contentType];
if(资源替换器的类型!=“函数”){
if(debug)casper.echo(“下载资源(“+resource.obj.contentType+”):“+url+”到“+resource.file”);
下载(url,resource.file,“GET”);
}否则{
资源替代者(资源);
}
}
forEach(函数(wrap){
//使用文档中的字符串测试资源url(从后面开始增长)
var-lastURL;