云函数是一段运行在云端的代码,无需管理服务器,在开发工具内编写、一键上传部署即可运行后端代码。云函数运行时基于node.js
云函数之爬取腾讯课堂课程好评体验步骤如下:
1、开通云开发功能及创建云开发项目(不赘述)
2、新建Node.js云函数:右击【cloudFuns】>新建Node.js云函数【getComments】
在本地创建node.js云函数后后上传到云环境中。
3、安装第三方网络请求包 request-promise【https://github.com/request/request-promise】
4、在目录【getComments】->【index.js】中爬取课程评价
// 云函数入口文件
const cloud = require('wx-server-sdk')
const rp=require("request-promise")
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
let course_id=event.course_id
//1.确定接口信息 https://ke.qq.com/cgi-bin/comment_new/course_comment_list?cid=420368&count=10&page=0&filter_rating=0&bkn=762645032&r=0.3031802187716004
//referer: https://ke.qq.com/course/420368?taid=3398075045800464
// 2.借助模块,向指定接口发送网络请求,获取数据,返回出去
let options = {
uri: 'https://ke.qq.com/cgi-bin/comment_new/course_comment_list',
qs: {
cid: course_id, //课程id
count: 10,
page: 0
},
headers: {
referer: `https://ke.qq.com/course/${course_id}?taid=3398075045800464`
},
json: true // Automatically parses the JSON string in the response
};
let result=await rp(options).then((res)=> {
return res
})
.catch( (err) =>{
console.log(err)
});
return result;
}
如何确定接口信息:在控制台中获取接口url、参数和refer
5、右击【getComments】目录->【上传并部署:云端安装依赖】,部署后如下图。
6.云函数调用-在页面中调用云函数
data: {
commentList:[]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
//调用云函数
wx.cloud.callFunction({
name:"getComments",
data:{
course_id:420368
// course_id:411679
},
success:res=>{
console.log("云函数调用成功",res.result.result.items)
this.setData({
commentList:res.result.result.items
})
},
fail:err=>{
console.log("云函数调用失败",err)
}
})
},