• node


    cherrio模块

    安装
    cnpm install cherrio
    
    使用方法
    const cheerio = require('cheerio')
    const $ = cheerio.load('<h2 class="title">Hello world</h2>')
     
    $('h2.title').text('Hello there!')
    $('h2').addClass('welcome')
     
    $.html()
    //=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
    

    request模块

    var request = require('request');
    request('http://www.google.com', function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred
      console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
      console.log('body:', body); // Print the HTML for the Google homepage.
    });
    

    爬虫系统 request cheerio

    1. 爬取一个网站的内容信息
    2. 分析内容
    3. 储存数据 下载图片

    简单的爬虫

    //发起服务端请求 请求一个网页 
    const request = require('request')
    const  fs= require('fs')
    const path= require('path') 
    const cheerio = require('cheerio')
    //以百度为例
    let url ='https://www.baidu.com/'
    request(url,(err,response,body)=>{
     console.log(err)
     //把爬取到的body 写入新文件中
      fs.writeFile(path.join(__dirname,'./baidu.html'),body,(err)=>{
        if(err){
          console.log('爬取失败')
        }else{
          console.log('爬取成功')
        }
      })
    //根据一个网址 下载对应的网页文件
    const $ = cheerio.load(body)
    let imgs = []
    // 用正则判断数组中的路径是否存在https
    var Reg = /(http[s]?|ftp)/;
    $('img').each((index, ele) => {  // 遍历所有
        var src = $(e).attr('src');
        if (!Reg.test(src)) {
            src = src.replace(//{2}/, 'https://') //正则判断
        }
        imgs.push(src)
    })
    // 下载数组里的图片
    for (let index = 0; index < imgs.length; index++) {
        if (imgs[index].indexOf('png') !== -1) {
            request(imgs[index]).pipe(fs.createWriteStream(`./img/${index}.png`))    //用下标命名,要建好img文件夹
        };
        
    }
    })
    
  • 相关阅读:
    Ext.Net中,文件下载。
    Ext.Net中,DataView数据绑定之使用技巧。
    Ext.Net控件,简单案例1,让我们从Hello World开始,走进Ext.Net控件的世界!。
    VSCode入门设置成中文
    S2T40,第四章,简答4
    MongoDB学习笔记三:查询
    初等数论学习笔记一:整除的概念与带余除法
    MongoDB学习笔记四:索引
    初等数论学习笔记二:最大公因数与辗转相除法
    MongoDB学习笔记二:创建、更新及删除文档
  • 原文地址:https://www.cnblogs.com/zhaoxinran997/p/12177589.html
Copyright © 2020-2023  润新知