[英]Loop through pages and return product links in single array
我有通過一些幫助獲得的代碼,可以在此處的此鏈接中找到。 它原則上運行良好,但問題是它分別為每個頁面返回鏈接和 arrays。 但是,我希望它為所有頁面一起返回鏈接和單個數組。 我需要創建一個字符串var all_links = []
並將每個頁面中的所有鏈接推入其中all_links.push(...links)
然后像return all_links
一樣返回它們但問題是我失敗了,因為我沒有在這種情況下不知道該怎么做。 我是一個純粹的初學者,沒有編碼方面的先驗知識
const puppeteer = require('puppeteer')
const minDiscount = 20;
async function getLinks() {
const browser = await puppeteer.launch({
headless: false,
defaultViewport: null,
});
const page = await browser.newPage();
const url = 'https://www.mytoys.de/spielzeug-spiele/holz/';
await page.goto(url);
// getting all the products, this will return an array of ElementHandle
while(await page.$(".pager__link--next")){
await page.waitForSelector(".pager__link--next")
await page.waitForTimeout(1000);
await page.click('.pager__link--next')
await page.waitForTimeout(1500);
const products = await page.$$('.prod-grid.js-prod-grid .prod-grid__item.js-prod-grid_item');
const proms = await Promise.allSettled(
products.map(async (prod) => {
// searching for a discount on each product
const disc = await prod.$$eval(
'.prod-grid.js-prod-grid .prod-flag.prod-flag-sale',
(discount) =>
discount.map((discItem) =>
discItem.innerText.replace(/[^0-9.]/g, '').replace(/\D+/g,'0')
)
);
// if it has a discount
if (disc.length > 0) {
// we parse the discount to Integer type to compare it to minDiscount
const discountInt = parseInt(disc[0], 10);
if (discountInt >= minDiscount) {
// we get the link of the product
const link = await prod.$$eval('.prod-grid.js-prod-grid .prod-tile__link.js-prodlink', (allAs) => allAs.map((a) => a.href));
if (link.length > 0) {
// push an object containing the discount and the link of the product
return link[0];
}
}
}
return null;
})
);
const bulkArray = proms.map((item) => {
if (item.status === 'fulfilled') return item.value;
});
const endArray = bulkArray.filter(item => item !== null);
console.log(endArray);
}
}
getLinks();
請幫助和仁慈,因為我剛剛開始學習基礎知識
這是一個讓你開始的清理工作:
const products = await page.$$eval('.prod-tile', divs => divs.map(div => {
return {
url: div.querySelector('a')?.href
discount: div.querySelector('.prod-flag-sale')?.innerText
}
}))
此時只需點擊下一個鏈接並為每個頁面做同樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.