我正在构建一个类似于 Flipboard 简报移动应用程序的报纸应用程序!使用 nodejs nestjs 框架。
因此,我正在爬入多个网站以获取数据,最终我得到了一个数组,其中包含 60 多个项目,仅用于从每个网站收集的第一页,响应时间在 10 到 15 秒之间,这对于仅 3 个网站来说是不可接受的!! !!
我搜索了这个,我发现 nestjs 提供了一个缓存服务,缓存结果以 20 毫秒结束,这很棒,但是!
我没有使用任何类型的数据库,因为我没有抓取数据!只是 iframe 的标题和 URL
我的问题是:
如何对每页 60 个项目进行分页,并最终从我的爬虫中发出对下一页的新请求。
第一个用户将面临每 6 小时 15 秒的响应时间(我的缓存结束)那么如何让服务器自动缓存数据而不是等待请求
爬虫代码:(我有 3 个类似的函数,只是 CSS 选择器发生了变化)
async getArticlesFromTechWD(page: number) {
const html = await get('https://www.tech-wd.com/wd/category/news/page/' + page);
// Cheerio
let $ = load(html);
function formatingDate(date) {
let months = ["يناير", "فبراير", "مارس", "إبريل", "مايو", "يونيو",
"يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"
];
date = date.replace('،', '').split(' ');
const year = date[2];
const month = (months.indexOf(date[1]) + 1).toString().length == 1 ? '0' + (months.indexOf(date[1]) + 1) : (months.indexOf(date[1]) + 1)
const day = date[0];
return `${year}-${month}-${day}`;
}
const articles = $('#masonry-grid .post-element').map(function () {
return {
title: $('.thumb-title', this).text().trim(),
date: formatingDate($('.date', this).text().trim()),
url: $('.thumb-title a', this).attr('href'),
image: $('.slide', this).css('background-image').replace('url(', '').replace(')', '').replace(/\"/gi, ""),
src: 'www.tech-wd.com'
}
}).get();
return articles;
}
将所有爬虫数据合并到一个数组中:
async getAllArticles(page: number, size: number) {
const skip = size * (page - 1);
// First crawler ( has an optional page pram default is page 1 )
const unlimitTech = await this.getArticlesFromUnlimitTech();
// Second crawler ( has an optional page pram default is page 1 )
const tectWd = await this.getArticlesFromTechWD();
// Merge them and sorted by date ( DESC )
const all = unlimitTech.concat(tectWd).sort(() => Math.random() - 0.5);
return all;
}
交互式爱情
一只甜甜圈
相关分类