写⼀个简单node爬⾍,将苑⼀峰es6教程⽹爬取转为pdf⽂件
准备⼯作,很简单,只需要安装好node 环境就可以了,另外安装⼀个⾕歌开发的⼀个爬⾍框架,puppeteer,这个模块很强⼤,可以模拟浏览器做很多事情,⼤家可以去官⽹去学习⼀下,不多说,直接上代码
// 爬取苑⼀峰  es6 教程⽹将⽹页转为pdf ⽂件
const puppeteer = require("puppeteer");
const fs = require("fs");
const path = require("path")
nodeselectorconst staticPath = "/theme"; //静态资源⽬录
class Index{
constructor(){
this.host="es6.ruanyifeng/",
this.arrTile = [];
this.browser = null;
this.page = null;
this.pathName = null;
    this.init()
}
async init(){
try {
this.browser = await puppeteer.launch();//打开浏览器
Title(); //获取所有链接
//await this.mkdir(); //⽣成指定⽂件夹
await this.writerAllPdf();//⽣成所有pdf
await this.writerOnePdf("es6.ruanyifeng/#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  wPage(); //创建⼀个新窗⼝
(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 wPage();
try {
(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();

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。