码迷,mamicode.com
首页 > 移动开发 > 详细

使用 nodejs 和 axios 以及 cherrio 爬取天气预报

时间:2018-11-27 01:33:30      阅读:405      评论:0      收藏:0      [点我收藏+]

标签:data   turn   console   UNC   www   天气预报   get   ror   find   

  1. 安装依赖
  2. 引入依赖
  3. 发送请求
  4. 解析请求的返回值
const axios = require(‘axios‘)
const cheerio = require(‘cheerio‘)


axios.get(‘http://www.weather.com.cn/weather/101280601.shtml‘)
    .then(function (response) {
      const $ = cheerio.load(response.data)
      var data = [];
      $(‘#7d li‘).each(function(){
          var $this = $(this);

          // 使用trim去掉数据两端的空格
        data.push({
              title : trim($this.find(‘.sky h1‘).text()),
              wea: trim($this.find(‘.sky .wea‘).text()),
              leg: trim($this.find(‘.sky .tem‘).text())
            });
      })

      function trim(str){
        return str.replace(/(^\s*)|(\s*$)/g, "");
      }

      console.log(data)
})
.catch(function (error) {
  console.log(error);
});

以上代码可以复制直接运行,获得 7 天的天气预报

使用 nodejs 和 axios 以及 cherrio 爬取天气预报

标签:data   turn   console   UNC   www   天气预报   get   ror   find   

原文地址:https://www.cnblogs.com/zhourongcode/p/10023690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!