最近才注意到微信小程序增加了個(gè)云開發(fā),手上項(xiàng)目不多就趕緊試試手,新增加云函數(shù)和云數(shù)據(jù)庫;云函數(shù)就類似于服務(wù)端,云函數(shù)其實(shí)就是封裝了mongdb,不過小程序js中可以直接操作數(shù)據(jù)庫,只是與云函數(shù)對的操作權(quán)限不同
云控制臺:
開始我的項(xiàng)目,我利用云函數(shù)中科可以使用node模塊,于是就試試能不能寫個(gè)爬蟲小程序
const cheerio = require("cheerio"); //進(jìn)入cheerio模塊
let charset = require('superagent-charset'); //解決亂碼問題:
let superagent = require('superagent'); //發(fā)起請求
charset(superagent);
cloud.init()
// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
let servceUrl = "https://xxxx/"
const result = await superagent
.get(servceUrl)
.charset('gb2312'); //取決于網(wǎng)頁的編碼方式
const data = result.text || '';
const $ = cheerio.load(result.text);
let hotList = $('.hot').find('.image');
let classifyList = $('.block');
let hotData = [];//熱榜
let classifyData = [];//分類推薦
for (let i = 0; i < hotList.length;i++){
let obj = {};
obj['url'] = $(hotList[i]).find('a').attr('href');
obj['imgurl'] = $(hotList[i]).find('img').attr('src');
obj['name'] = $(hotList[i]).find('img').attr('alt');
obj['autho'] = $(hotList[i]).next().find('dt').find('span').text();
obj['detail'] = $(hotList[i]).next().find('dd').text();
hotData.push(obj)
}
for (let i = 0; i < classifyList.length; i++) {
let obj = {};
let childData = []
let childDom = $(classifyList[i]).find('.lis').find('li');
for (let j = 0; j < childDom.length;j++){
let chilObj = {};
chilObj['name'] = $(childDom[j]).find('.s2').find('a').text();
chilObj['url'] = $(childDom[j]).find('.s2').find('a').attr('href');
chilObj['autho'] = $(childDom[j]).find('.s3').text();
childData.push(chilObj);
}
obj['classifyList'] = $(classifyList[i]).find('h2').text();//類別名稱
// obj['childDom'] = childDom.length;
obj['data'] = childData;
classifyData.push(obj)
}
return {
classifyData,
hotData
};
}
果然是沒問題的,不過中間需要注意開始npm的構(gòu)建,還可以引入ui,推薦vantui,基本功能都有,中間由于有些編碼問題做了一些處理,上面是我云函數(shù)的代碼,下面是如何調(diào)用云函數(shù):
主要代碼: wx.cloud.callFunction({
name:'getList',
data:{}
}).then(res=>{
wx.hideLoading ();
console.log(res.result);
const result = res.result || {};
this.setData({
hotdata: result.hotData,
classtyf: result.classifyData
})
}).catch(err=>{
wx.hideLoading ();
console.log(err)})
},
中間還涉及到閱讀記錄的保存,于是我簡單實(shí)用了云數(shù)據(jù)庫:
代碼簡單示意,文檔里面都有哈,我用到的兩張表
今天分享到此。