[英]How do I write data from NightmareJS to file
I'm new to JavaScript, node.js, and NightmareJS. 我是JavaScript,node.js和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!');
});
I keep getting the error shown below: 我一直收到如下错误:
return binding.writeString(fd, buffer, offset, length, req);
^
TypeError: First argument must be file descriptor
Function contents inside of .evaluate()
are run in the browser context. .evaluate()
内的函数内容在浏览器上下文中运行。 As such, fs
and data
won't be lifted into the function scope you've defined. 因此,
fs
和data
不会被提升到您定义的功能范围内。 (You can read more about variable lifting and .evaluate()
here .) (您可以在此处阅读有关变量提升和
.evaluate()
更多信息。)
fs.write()
won't work as you intend - fs.write()
is asynchronous . fs.write()
将无法正常工作 - fs.write()
是异步的 。
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. 另外,我怀疑
$(selector).text()
会产生你想要的结果 - 我认为这会将每个链接的链接文本连接在一起。 I suspect you want them in an array? 我怀疑你想要他们在一个阵列?
Furthermore, I should point out that .run()
isn't directly supported . 此外,我应该指出
.run()
不是直接支持的 。 It's an internal function, kept around mostly for compatibility. 这是一个内部功能,主要是为了保持兼容性。
Finally, it would appear you're using either a custom build of jQuery or a third party library to get XPath support. 最后,看起来你正在使用自定义构建的jQuery或第三方库来获得XPath支持。 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);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.