美文网首页
nodejs爬虫制作

nodejs爬虫制作

作者: 辉夜乀 | 来源:发表于2017-07-25 14:57 被阅读37次
/*超简易的一个爬虫,爬慕课网的数据,并做处理*/

const http = require('http')
const cheerio = require('cheerio')
const url = 'http://www.imooc.com/learn/348'

//http模块发出get请求,执行回调函数
http.get(url, (res) => {
  var html = ''

  //res触发data事件,拼接html字符串
  res.on('data', (data) => {
    html += data
  })

  //res最后触发end事件,输出html字符串源码
  res.on('end', () => {
    let courseData = filterChapters(html) //res结束后,把拼装好的html过滤处理
    printCourseInfo(courseData)
  })
}).on('error', () => {
  console.log('获取数据出错!');
})

//用cheerio模块解析获取的html字符串,爬取数据
function filterChapters(html) {
  let $ = cheerio.load(html)
  let chapters = $('.chapter')

  // 期望获取的数据结构
  //   [{
  //     chapterTitle: '',
  //     videos: [{
  //       title: '',
  //       id: ''
  //     }]
  //   }]

  let courseData = []

  chapters.each((index, item) => { //不能用箭头函数,因为没有this
    let chapter = $(item) //用箭头函数就要找出回调,回调参数log大法找
    let chapterTitle = chapter.find('h3 strong').text()
    let videos = chapter.find('.video').children('li')
    let chapterData = {
      chapterTitle,
      videos: []
    }

    videos.each((index, item) => { //不能用箭头函数,因为没有this
      let video = $(item) //用箭头函数就要找出回调,回调参数log大法找
      let videoTitle = video.find('.J-media-item').text()
      let id = video.data('media-id')
      chapterData.videos.push({
        title: videoTitle,
        id: id
      })
    })

    courseData.push(chapterData)
  })
  return courseData
}

//打印出爬取信息
function printCourseInfo(courseData) {
  courseData.forEach((item) => {
    let chapterTitle = item.chapterTitle
    console.log(chapterTitle);
    item.videos.forEach((video) => {
      console.log(`[${video.id}] ${video.title}`);
    })
  })
}

相关文章

  • nodejs爬虫制作

  • nodeJS爬虫(完整版)

    nodeJs爬虫

  • nodejs通过钉钉群机器人推送消息

    nodejs 通过钉钉群机器人推送消息 Intro 最近在用 nodejs 写爬虫,之前的 nodejs 爬虫代码...

  • NodeJs + Phantomjs 简易爬虫

    NodeJs + Phantomjs 简易爬虫 爬虫是什么? 引用百度百科的说法是: 如何在NodeJs上搭建爬虫...

  • Nodejs制作一只小爬虫

    前言   今天下午闲来无事,突然想学习一下爬虫技术了,就在网上看了点资料,然后自己亲手制作了一只小爬虫,在这里呢,...

  • Nodejs爬虫

    Node.js批量抓取高清妹子图片:https://cnodejs.org/topic/54bdaac4514ea...

  • NodeJS 爬虫

    技术栈cheerio: 将抓取的html直接转化为jquery对象,可以直接对获取信息进行DOM操作。puppet...

  • nodejs爬虫

    nodejs相关模块 获取网页内容(http\request\superagent等) 筛选网页信息(cheeri...

  • nodejs 爬虫

    爬取的是豆瓣网 本次将会用到两个库:superagent 和cheerio 其中 superagent是用来请求目...

  • nodejs - 爬虫

    继续上一篇写下爬虫的实现,网上找了一个爬虫的文章,然后从里面找了一个网址,https://www.lanvshen...

网友评论

      本文标题:nodejs爬虫制作

      本文链接:https://www.haomeiwen.com/subject/nxwwkxtx.html