我正在尝试获取一个博客 ( https://www.mrmoneymustache.com )文章的所有链接,以便我可以将它们编译成 pdf,但我完全是 javascript 新手。reddit 上有人告诉我使用这个代码,它应该做我想做的:
const fs = require('fs');
const EventEmitter = require('events').EventEmitter;
const fetch = require('node-fetch');
const cheerio = require('cheerio');
const e = new EventEmitter();
e.on('fetchPage', link => {
fetch(link).then(r => r.text()).then(cheerio.load).then($ => {
const nextLink = $(".next_post a").attr('href');
if (nextLink === undefined) return; // end on final page
const postTitle = $(".headline").text();
const postContent = $(".post_content").html();
console.log(postTitle);
fs.writeFileSync(postTitle + ".html", postContent);
setTimeout(() => e.emit('fetchPage', nextLink), 5000);
});
});
e.emit('fetchPage', 'https://whatever/post1');
但我真的不明白我应该如何运行这个程序.. 请帮忙?
安装Node.js,然后在命令 shell 中运行此命令:
node yourfile.js
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句