const express = require('express')
// cheerio相当于服务器端的jQuery
const cheerio = require('cheerio')
// superagent 是一个http请求库,我们利用它来获取页面内容
const superagent = require('superagent')
let app = express()
app.get('/', (req, res, next)=>{
superagent.get('https://cnodejs.org/')
.end((error, sres)=>{
if(error){
return next(error)
}
let items = []
// sres.text是请求的页面内容,将它传给cheerio.load就可以得到实现了JQuery接口的变量,我们习惯性的把它命名为$
let $ = cheerio.load(sres.text)
$('#topic_list .topic_title').each(function(idx, element) {
let $element = $(element)
items.push({
title: $element.attr('title'),
href: $element.attr('href')
})
})
res.send(items)
})
})
// 处理错误的中间件
app.use((error, req, res, next) => {
console.log(error)
res.status(error.status || 500).json({
message: error.message,
error: error.errno
})
})
app.listen(3000, function() {
console.log('app is listening at port 3000')
})
以上代码抓取了CNode社区首页帖子的标题和链接,用到了express, cheerio,superagent三个开源库,感兴趣的可以去github深入了解一下,代码不是很难,就不做过多解释了,关键的地方代码上都有注释