时间:2021-07-10 09:31:29 | 栏目:NodeJS | 点击:次
本文介绍了Node.js 利用cheerio制作简单的网页爬虫示例,分享给大家,具有如下:
1. 目标
2. 代码部分
介绍: 获取segment fault页面的列表标题,将获取到的标题列表编号,最终输出到pageTitle.txt文件里
const https = require('https'); const fs = require('fs'); const cheerio = require('cheerio'); const url = 'https://segmentfault.com/'; https.get(url, (res) => { let html = ''; res.on('data', (data) => { html += data; }); res.on('end', () => { getPageTitle(html); }); }).on('error', () => { console.log('获取网页信息错误'); }); function getPageTitle(html) { const $ = cheerio.load(html); let chapters = $('.news__item-title'); let data = []; let index = 0; let fileName = 'pageTitle.txt'; for (let i = 0; i < chapters.length; i++) { let chapterTitle = $(chapters[i]).find('a').text().trim(); index++; data.push(`\n${index}, ${chapterTitle}`); } fs.writeFile(fileName, data, 'utf8', (err) => { if (err) { console.log('fs文件系统创建新文件失败', err); } console.log(`已成功将获取到的标题放入新文件${fileName}文件中`) }) }