簡體   English   中英

如何從單個數組中的多個頁面獲取鏈接

[英]How to get links from multiple pages in a single array

我有一個工作代碼,可以成功地從多個頁面中獲取所有產品鏈接,這些頁面至少有 20% 的折扣。 唯一的問題是它分別為每個頁面返回 arrays 中的鏈接。 但是,我希望它返回單個數組中所有頁面的鏈接,然后將它們傳輸到另一個 function。 我嘗試創建一個字符串 var all_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();

我目前獲得的結果示例

[
  'https://www.mytoys.de/erzi-kinderwurst-sortiment-spiellebensmittel-6749036.html',
  'https://www.mytoys.de/chr-tanner-spiellebensmittel-wurststaender-1031946.html',
  'https://www.mytoys.de/hape-xylophon-und-hammerspiel-2503719.html',
  'https://www.mytoys.de/erzi-kinderparty-spiellebensmittel-6749035.html',
]
[
  'https://www.mytoys.de/brio-holzeisenbahnset-landleben-5501952.html',
  'https://www.mytoys.de/brio-brio-33277-bahn-ir-reisezug-set-4592516.html',
  'https://www.mytoys.de/brio-parkhaus-strassen-schienen-3175226.html',
  'https://www.mytoys.de/mytoys-steckwuerfel-12-tlg-11389814.html',
  'https://www.mytoys.de/brio-schienen-und-weichensortiment-1758325.html',
]
[
  'https://www.mytoys.de/hape-grosser-baukran-4141517.html',
  'https://www.mytoys.de/noris-mein-buntes-tuermchenspiel-3421170.html',
  'https://www.mytoys.de/goki-ziehtier-schaf-suse-2488933.html',
  'https://www.mytoys.de/eichhorn-colorsoundzug-mit-licht-1521635.html',
]

您希望獲得的結果示例

[
  'https://www.mytoys.de/erzi-kinderwurst-sortiment-spiellebensmittel-6749036.html',
  'https://www.mytoys.de/chr-tanner-spiellebensmittel-wurststaender-1031946.html',
  'https://www.mytoys.de/hape-xylophon-und-hammerspiel-2503719.html',
  'https://www.mytoys.de/erzi-kinderparty-spiellebensmittel-6749035.html',
  'https://www.mytoys.de/brio-holzeisenbahnset-landleben-5501952.html',
  'https://www.mytoys.de/brio-brio-33277-bahn-ir-reisezug-set-4592516.html',
  'https://www.mytoys.de/brio-parkhaus-strassen-schienen-3175226.html',
  'https://www.mytoys.de/mytoys-steckwuerfel-12-tlg-11389814.html',
  'https://www.mytoys.de/brio-schienen-und-weichensortiment-1758325.html',
  'https://www.mytoys.de/hape-grosser-baukran-4141517.html',
  'https://www.mytoys.de/noris-mein-buntes-tuermchenspiel-3421170.html',
  'https://www.mytoys.de/goki-ziehtier-schaf-suse-2488933.html',
  'https://www.mytoys.de/eichhorn-colorsoundzug-mit-licht-1521635.html',
]
  1. 在循環之前為鏈接收集聲明新變量:
const allLinks = []; // <--
while(await page.$(".pager__link--next")){ ... }
  1. 將所有鏈接推入其中:
...
const endArray = bulkArray.filter(item => item !== null);
console.log(endArray);
allLinks.push(endArray); // <--
  1. 循環執行后返回/記錄結果:
async function getLinks() {
  ...
  return allLinks.flat(); // <--
}

console.log(await getLinks()) // result array

參考: Array.prototype.flat()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM