我正在尝试使用node.js,cheerio和puppeteer编写抓取脚本。
我目前遇到的问题是试图使该writeFile()
功能正常工作。
const puppeteer = require('puppeteer');
const $ = require('cheerio');
const fs = require('fs');
const url = 'https://www.made-up-url.com/';
puppeteer
.launch()
.then(function(browser) {
return browser.newPage();
})
.then(function(page) {
return page.goto(url).then(function() {
return page.content();
});
})
.then(function(html) {
let scrapedTitle = $('h1', html).each(function() {
return $(this).text();
});
let scrapedDesc = $('#something-else > div > p', html).each(function() {
return $(this).text();
});
// Both console logs are outputted as strings, as expected
console.log(scrapedTitle[0].children[0].data); // "Some title"
console.log(scrapedDesc[0].children[0].data); // "The description is like this."
fs.writeFile("data.json", JSON.stringify(scrapedTitle[0].children[0].data), 'utf8', function(err) {
if(err) {
return console.log(err);
}
console.log("The data has been scraped and saved successfully! View it at './data.json'");
});
process.exit();
})
.catch(function(err) {
console.log(err);
process.exit();
});
writeFile()
过去曾使用过类似的东西fs.writeFile("data.json", JSON.stringify(html), 'utf8', function(err) {
,但现在似乎也没有用。当我运行此脚本时,将按预期方式创建文件,但该文件始终为空,即使两者都console.log()
显示应该写入有效的字符串也是如此。没有错误。有什么想法吗?
您在下面的行中,Theprocess.exit();
正在关闭文件写操作之前的过程:
fs.writeFile("data.json", JSON.stringify(scrapedTitle[0].children[0].data), 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log("The data has been scraped and saved successfully! View it at './data.json'");
});
process.exit();
您可以将其更改为如下所示,以便在关闭文件之前完成文件写入操作:
fs.writeFile("data.json", JSON.stringify(scrapedTitle[0].children[0].data), 'utf8', function(err) {
if(err) {
return console.log(err);
process.exit();
}
console.log("The data has been scraped and saved successfully! View it at './data.json'");
process.exit();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句