1. 程式人生 > 實用技巧 >寫一個簡單node爬蟲,將苑一峰 es6 教程網爬取轉為pdf 檔案

寫一個簡單node爬蟲,將苑一峰 es6 教程網爬取轉為pdf 檔案

準備工作,很簡單, 只需要安裝好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();