PhantomJS/Javascript:下载网页并写入文本文件
下面的代码是下载网页它的工作很好,但我想保存我把代码写的文本文件老实说,我不知道我怎么可以这样做来保存文件PhantomJS/Javascript:下载网页并写入文本文件,phantomjs,Phantomjs,下面的代码是下载网页它的工作很好,但我想保存我把代码写的文本文件老实说,我不知道我怎么可以这样做来保存文件 var url = 'http://stackoverflow.com'; var page = require('webpage').create(); page.open(url, function(status) { if (status === 'success') { var html = page.evaluate(function() {
var url = 'http://stackoverflow.com';
var page = require('webpage').create();
page.open(url, function(status) {
if (status === 'success') {
var html = page.evaluate(function() {
return document.documentElement.outerHTML;
});
console.log(html);
}
var fs = require('fs');
try {
fs.write("C:\phantomjs\\qhxpZ.txt", "Message to be written to the file", 'w');
} catch(e) {
console.log(e);
}
phantom.exit();
});
只需将“要写入文件的消息”替换为html即可保存文件
fs.write("C:\phantomjs\\qhxpZ.txt", "Message to be written to the file", 'w');
因此,为了完整性,手头问题的解决方案应该如下所示:
var url = 'http://stackoverflow.com';
var fs = require('fs');
var page = require('webpage').create();
page.open(url, function(status) {
if (status === 'success') {
var html = page.evaluate(function() {
return document.documentElement.outerHTML;
});
try {
fs.write("C:\\phantomjs\\qhxpZ.txt", html, 'w');
} catch(e) {
console.log(e);
}
}
phantom.exit();
});
此外,请确保路径正确。您可能希望有
C:\\phantomjs\\qhxpZ.txt
(两个都有\double。)page.content不包含DHTML JavaScript对页面的更改;outerHtml没有。(函数(导出、require、模块、文件名、目录名){var page=require('webpage')。create(),