准备工作,很简单, 只需要安装好node 环境就可以了,另外安装一个谷歌开发的一个爬虫框架,puppeteer,这个模块很强大,可以模拟浏览器做很多事情,大家可以去官网去学习一下,不多说,直接上代码

// 爬取 苑一峰  es6 教程网 将网页转为pdf 文件
const puppeteer = require("puppeteer");
const fs = require("fs");
const path = require("path")
const staticPath = "/theme"; //静态资源目录
class Index{
    
    constructor(){
        this.host="http://es6.ruanyifeng.com/",
        this.arrTile = [];
        this.browser = null;
        this.page = null;
        this.pathName = null;
     this.init() } async init(){
try { this.browser = await puppeteer.launch();//打开浏览器 await this.getTitle(); //获取所有链接 //await this.mkdir(); //生成指定文件夹 await this.writerAllPdf();//生成所有pdf await this.writerOnePdf("http://es6.ruanyifeng.com/#docs/class","Class 的基本语法");//生成单个pdf await this.browser.close(); //关闭浏览器 // return await {code:200,msg:"success",src:`${origin}/${relvaPath}${fileName}`}; } catch (error) { console.log(error) return await {code:-104,msg:"fail"} } } async getTitle(){ //获取所有链接 var page = await this.browser.newPage(); //创建一个新窗口 await page.goto(this.host); //跳转一个链接 await page.waitFor(1000) this.arrTile = await page.evaluate(() => { var list = [...document.querySelectorAll('#sidebar ol li')] return list.map(el => { var title= el.querySelector("a").innerText; var href = el.querySelector("a").href; return {title,href} }) }) await page.close(); } async writerOnePdf(href,fileName){ //将下载的网页保存pdf ,参数:页面链接,生成的pdf 文件名 var page = await this.browser.newPage(); try { await page.goto(href); await page.waitFor(1000); await page.pdf({path: `${this.pathName}/${fileName}.pdf`,format: 'A4'}); await page.close(); console.log(`${href} success ....`); } catch (error) { console.log(error) console.log(`${href} fail ....`); await page.close(); } } async writerAllPdf(){ //爬取所有的页面的pdf for (var i=0;i<this.arrTile.length;i++) { await this.writerOnePdf(this.arrTile[i].href,this.arrTile[i].title) } } async mkdir(){ //生成pdf 的文件夹 this.pathName = await path.join(process.cwd(),staticPath,"pdf","es6-pdf"); //保存的绝对路径 await mkdirSync(this.pathName); //判断文件路径(没有则创建) } } // * 创建目录 // * @param {*} dirname 绝对路径 // */ async function mkdirSync(dirname) { if (fs.existsSync(dirname)) { return true; } else { if (await mkdirSync(path.dirname(dirname))) { fs.mkdirSync(dirname); return true } } }

new Index();