我正在構建一個類似于 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;}
Nodejs/nestjs:從我的多個爬蟲獲得 13 秒的響應時間
哈士奇WWW
2021-11-04 16:02:47