1. 目标
- 完成对网站的标题信息获取
- 将获取到的信息输出在一个新文件
- 工具: cheerio,使用npm下载npm install cheerio
- cheerio的API使用方法和jQuery的使用方法基本一致
- 如果熟练使用jQuery,那么cheerio将会很快上手
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}文件中`)
})
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本网站。
您可能感兴趣的文章:
- node.js爬虫框架node-crawler初体验
- Node.js爬虫如何获取天气和每日问候详解
- node.js 基于cheerio的爬虫工具的实现(需要登录权限的爬虫工具)
- 基于node.js实现爬虫的讲解
- node.js学习笔记之koa框架和简单爬虫练习
- 手把手教你用Node.js爬虫爬取网站数据的方法
- 浅谈Node.js爬虫之网页请求模块
- node.js做一个简单的爬虫案例教程