我正在使用 Nightmare 为今天的报纸创建一个自动下载器。我设法登录并转到指定页面。但是我找不到如何使用 Nightmare 下载文件。
var Nightmare = require('nightmare');
new Nightmare()
.goto('https://login.nrc.nl/login?service=http://digitaleeditie.nrc.nl/welkom')
.type('input[name="username"]', 'Username')
.type('input[name="password"]','Password')
.click('button[type="submit"]')
.wait()
.goto('http://digitaleeditie.nrc.nl/digitaleeditie/NH/2014/10/20141124___/downloads.html')
.wait()
.click('a[href="/digitaleeditie/helekrant/epub/nrc_20141124.epub"]')
.wait()
.url(function(url) {
console.log(url)
})
.run(function (err, nightmare) {
if (err) return console.log(err);
console.log('Done!');
});
我尝试通过单击下载按钮来下载文件。然而,这似乎不起作用。
最佳答案
当您单击应下载的内容时,PhantomJS(以及 CasperJS 和 Nightmare)不会触发下载(对话框)。所以,有必要自己下载。如果您可以找到该文件的 URL,则可以使用页面上下文中的 XMLHttpRequest 轻松下载该文件。
所以你需要交换
.click('a[href="/digitaleeditie/helekrant/epub/nrc_20141124.epub"]')
对于
.evaluate(function ev(){
var el = document.querySelector("[href*='nrc_20141124.epub']");
var xhr = new XMLHttpRequest();
xhr.open("GET", el.href, false);
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send();
return xhr.responseText;
}, function cb(data){
var fs = require("fs");
fs.writeFileSync("book.epub", data, "binary");
})
您还可以使用更新的方式请求二进制数据。
.evaluate(function ev(){
var el = document.querySelector("[href*='.pdf']");
var xhr = new XMLHttpRequest();
xhr.open("GET", el.href, false);
xhr.responseType = "arraybuffer";
xhr.send();
var bytes = [];
var array = new Uint8Array(xhr.response);
for (var i = 0; i < array.length; i++) {
bytes[i] = array[i];
}
return bytes;
}, function cb(data){
var fs = require("fs");
fs.writeFileSync("book.epub", new Buffer(data), "binary");
})
关于javascript - 使用 Nightmare 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27109563/