技术解析
休息天没事做,小菜鸡一个。请多多指教。
初始化一个请求的方法
const cheerio = require('cheerio');
const request = require('request');
const iconv = require('iconv-lite');
function http(url, decode = 'utf8') {
return new Promise((resolve, rejext) => {
request({ url, encoding: null }, function (error, response, body) {
if (!error && response.statusCode == 200) {
var buf = iconv.decode(body, decode);//获取内容进行转码
var $ = cheerio.load(buf); //初始化
resolve($)
} else {
rejext(error)
}
});
})
}
module.exports = http
使用
// 微博热搜
const http = require('./http')
let url = 'https://s.weibo.com/top/summary'
http(url)
.t大带宽服务器hen(res => {
var $ = res;
var table = $('#pl_top_realtimehot > table > tbody').find('tr .td-02 a')
var resData = []
table.each((i, e) => {
resData.push({
index: i,
title: $(e).text(),
url: "https://s.weibo.com" + $(e).attr('href')
})
})
console.log(resData);
})
.catch(err => {
console.log(err);
})