如何将NightmareJS中的数据写入文件 [英] How do I write data from NightmareJS to file

查看:195
本文介绍了如何将NightmareJS中的数据写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript,node.js和NightmareJS的新手。

I'm new to JavaScript, node.js, and NightmareJS.

我在下面写了一个简单的脚本来从网页中提取一些文字,而我想把它保存到文件中。

I've written a simple script below to extract some text from a webpage, and I would like to save it to a file.

var nightmare = require('nightmare');
var data = [];
var fs = require('fs');

var usda = new nightmare()
.goto('yyyy')
.wait(20000)
.inject('js', 'jquery.js')
.evaluate(function(){  
  data = $x('//a').text();  
  fs.write("testOutput.json", JSON.stringify(data), 'w');
})
.end()
.run(function (err, nightmare) {
    if (err) return console.log(err);
    console.log('Done!');
});

我一直收到如下错误:

return binding.writeString(fd, buffer, offset, length, req);
             ^
TypeError: First argument must be file descriptor


推荐答案

.evaluate()中的函数内容在浏览器上下文中运行。因此, fs data 将不会被提升到您定义的函数范围内。 (您可以阅读有关变量提升的更多信息和 .evaluate() 这里。)

Function contents inside of .evaluate() are run in the browser context. As such, fs and data won't be lifted into the function scope you've defined. (You can read more about variable lifting and .evaluate() here.)

fs.write() 无法按预期工作 - fs。 write()是异步的。

fs.write() won't work as you intend - fs.write() is asynchronous.

另外,我怀疑 $(selector).text() 将产生您想要的结果 - 我认为这将连接每个链接的链接文本。我怀疑你想要他们在一个数组吗?

Also, I doubt $(selector).text() is going to yield the results you want - I think that will concatenate the link text from each link together. I suspect you want them in an array?

此外,我应该指出 .run()不受直接支持。它是一个内部函数,主要是为了保持兼容性。

Furthermore, I should point out that .run() isn't directly supported. It's an internal function, kept around mostly for compatibility.

最后,看起来你正在使用自定义构建的jQuery或第三方库来获得XPath支持。在将来,包含这些信息会很有帮助。

Finally, it would appear you're using either a custom build of jQuery or a third party library to get XPath support. In the future, it would be helpful to include that information.

所有这些都说明了,让我们修补你的例子来帮助你入门。关闭袖口,这样的事情应该有效:

All of that said, let's patch up your example to get you started. Off the cuff, something like this should work:

var nightmare = require('nightmare');
var fs = require('fs');

var usda = new nightmare()
.goto('yyyy')
.wait(20000)
.inject('js', 'jquery.js')
.evaluate(function(){
  //using 'a', but this could be swapped for your xpath selector
  return $('a').toArray().map((a) => $(a).text());
})
.end()
.then(function(anchors){
  fs.writeFileSync('testOutput.json', JSON.stringify(anchors));
  console.log('Done!');
});
.catch(function(err){
  console.log(err);
})

这篇关于如何将NightmareJS中的数据写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆