基本信息
源码名称:nodejs爬虫入门级示例(cheerio)
源码大小:0.96KB
文件格式:.zip
开发语言:js
更新时间:2018-05-12
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍
需要执行 npm install 后,再运行node testcheerio.js即可


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}文件中`)
  })
}