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

  1. 安装依赖
  2. 引入依赖
  3. 发送请求
  4. 解析请求的返回值
  • 以下代码可以复制直接运行,获得 7 天的天气预报
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);
});