• Nodejs小爬虫


    记得先装载http这个模块

    打开cmd  :npm install http -g

    var http=require('http')
    var url='http://www.imooc.com/learn/348'
    
    http.get(url,function(res){
    var html=''
    res.on('data',function(data){
    html +=data
    })
    res.on('end',function(){
    console.log(html)
    })
    }).on('error',function(){
    console.log('获取出错')
    })
    

      

    cmd:node一下,出来网页源码

    然后npm install cheerio -g

    用慕课网做测试哈哈哈  ,这里要说明一点:代码和课程中是不一样的,因为网站改动了源代码,class之类的名字换掉了,所以之前的爬虫爬不出来的。还好知道原理以后自己去改就可以了。

    /**
     * Created by Amy on 2017/7/13.
     */
    var http= require('http')
    var cheerio= require('cheerio')//先装载这个模块
    var url='http://www.imooc.com/learn/348'
    function filterChapters(html){
        var $=cheerio.load(html)
        var chapters= $('.chapter')
        // [{
        //     chapterTitle:'',
        //     videos:[
        //         title:'',
        //          id:''
        //     ]
        // }]
        var courseData=[]
        chapters.each(function(item){
            var chapter=$(this)
            var chapterTitle=chapter.find('strong').text()
            var videos=chapter.find('.video').children('li')
            var chapterData={
                chapterTitle:chapterTitle,
                videos:[]
            }
            videos.each(function(item){
                var video= $(this).find('.J-media-item')
                var videoTitle=video.text()
                var id = video.attr('href').split('video/')[1]
    
                chapterData.videos.push({
                    title:videoTitle,
                    id:id
                })
            })
            courseData.push(chapterData)
        })
        return courseData
    }
    function  printCourseInfo(courseData){
        courseData.forEach(function(item){
            var chapterTitle=item.chapterTitle
    
            console.log(chapterTitle+'
    ')
            item.videos.forEach(function(video){
                console.log('['+video.id+']'+video.title+'
    ')
            })
        })
    }
    http.get(url,function(res){
        var html=''
        res.on('data',function(data){
            html +=data
        })
        res.on('end',function(){
            var courseData=  filterChapters(html)
            printCourseInfo(courseData)
        })
    }).on('error',function(){
        console.log('获取出错')
    })
    

      去node一下试试,好神奇吧。

  • 相关阅读:
    sun.misc.BASE64Encoder找不到的解决方法
    eclipse里大小写转化的快捷键是什么
    jface viewer 理解
    如何在遗留代码基础上开发
    谈谈技术文档的编写
    jre build path 中的限制问题导致一些代码无法编译..如果设置
    android update automatically ( android 自动升级)
    各大集群存储产品点评
    关于@Autowired 注释为何不需要get Set
    VRML之desk
  • 原文地址:https://www.cnblogs.com/Amy-is-a-fish-yeah/p/7163784.html
Copyright © 2020-2023  润新知