如何用p操纵者刮取src图像?

时间:2020-06-10 07:11:39

标签: javascript puppeteer

我需要来自弹出链接的src图像。 https://www.tokopedia.com/pusatvalve/1-2-inch-ball-valve-sankyo-mojekerto 我已经尝试过了

const popup = await page.$('div.css-hnnye.ew904gd0');
    const maxLoop = await page.evaluate(() => {
      let contain = document.querySelectorAll('div.css-1muhp5u.ejaoon00');
      return contain.length;
    });

    let image1 = '';
    let image2 = '';
    let image3 = '';
    let image4 = '';
    let image5 = '';

    if (0 <= Number(maxLoop)) {
      image1 = await popup.evaluate( popup => {
        popup.click()
        let image = document.querySelector('img.css-udmgcf').src;
        return image;
      } );
    }

    await page.keyboard.press('Escape');
    await page.keyboard.up('Escape');
    await page.click('div.css-xwybk > div > div > div:nth-child(2) > div');

    const popup2 = await page.$('div.css-hnnye.ew904gd0');

    if (1 <= Number(maxLoop)) {
      image2 = await popup2.evaluate( popup2 => {
        popup2.click()
        let image = document.querySelector('img.css-udmgcf').src;
        return image;
      } );
    }

    image1 !== '' ? item.image1 = image1 : '';
    image2 !== '' ? item.image2 = image2 : '';
    image3 !== '' ? item.image3 = image3 : '';
    image4 !== '' ? item.image4 = image4 : '';
    image5 !== '' ? item.image5 = image5 : '';

,但结果始终是相同的图片。 result

注意:我想获取格式src .jpeg enter image description here

1 个答案:

答案 0 :(得分:0)

您可以尝试执行以下操作:

const puppeteer = require('puppeteer')

const PAGE_URL = ' ... ' // the page to scrap the images from

const browser = puppeteer.launch({
    headless: true
});

(async function () {
    const page = await (await browser).newPage()

    await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36');
    await page.setViewport({ width: 960, height: 768 });

    await page.goto(PAGE_URL, {
        timeout: 60000
    })

    const scrappedImages = await page.evaluate(async () => {
        const asyncSleep = (ms) => new Promise((rs, _) => setTimeout(rs, ms))

        const images = []

        for (const eachThumbnail of document.querySelectorAll("div[data-testid='PDPImageThumbnail'] > div > img")) {
            await eachThumbnail.click()

            let imageSrc = document.querySelector("div[data-testid='PDPImageMain'] > div > div > img").src

            while (images.includes(imageSrc) || imageSrc.startsWith('data:')) {
                imageSrc = document.querySelector("div[data-testid='PDPImageMain'] > div > div > img").src;
                await asyncSleep(1000)
            }

            images.push(imageSrc)
        }

        return images
    })

    console.log(scrappedImages)

})()

此处脚本使用data-testid属性来选择元素,因为它比div.css-xwybk或其他类似的类名(我认为会经常更改)更稳定。

另一件事是,由于缩略图的大小不是原始大小,因此脚本会单击它们并等待,直到呈现原始图像,然后再存储URL。 (还避免使用base64图像src,因为这些图像用于显示加载指示符。)

注意::在对任何网站进行任何自动化操作之前,请确保不要禁止正在执行的操作或违反该网站的政策。 (此答案严格是为了向您显示如何使用p来达到此目的,而不是鼓励您这样做)