get img src on google images with puppeteer

佐手、 提交于 2021-01-28 07:03:18

问题


Im doing a small script, and i want it to get a src from the first image on google photos, i have tried so many things, but i havent been able to get the src and save it into a variable. This is the script so far, i will be very grateful if you help me.

const puppeteer = require('puppeteer');
let imgSrc

(async () => {
    const browser = await puppeteer.launch({
        headless: false,
    });
    const page = await browser.newPage();
    await page.setViewport({
        width:1920,
        height:1080,
        isMobile: false
    })
    await page.goto('https://www.google.com/imghp');
    await         page.waitForXPath('/html/body/div[2]/div[2]/div[2]/form/div[2]/div[1]/div[1]/div/div[2]/input')
    await page.click('#sbtc > div > div.a4bIc > input')
    await page.type('#sbtc > div > div.a4bIc > input', 'Tiras Glucomet Freestyle Optimun 50 unidades y 100 unidades')
    await page.click('#sbtc > button > div > span > svg')
    await page.waitForXPath('/html/body/div[2]/c-wiz/div[3]/div[1]/div/div/div/div/div[1]/div[1]/div[1]/a[1]/div[1]/img')
    await page.click('#islrg > div.islrc > div:nth-child(1) > a.wXeWr.islib.nfEiy.mM5pbd > div.bRMDJf.islir > img')
    await page.waitForXPath('/html/body/div[2]/c-wiz/div[3]/div[2]/div[3]/div/div/div[3]/div[2]/c-wiz/div[1]/div[1]/div/div[2]/a/img')
    const data = await page.evaluate(() => {
        let src = document.querySelector('#Sva75c > div > div > div.pxAole > div.tvh9oe.BIB1wf > c-wiz > div.OUZ5W > div.zjoqD > div > div.v4dQwb > a > img').getAttribute('src')
        imgSrc = src
    })
    console.log(imgSrc)
})();

回答1:


The code in function argument оf page.evaluate() is executed in browser context so it has not acces to variables of the puppeteer context including imgSrc. You need to transfer the data and then assign it to the variable:

    imgSrc = await page.evaluate(() => {
        let src = document.querySelector('#Sva75c > div > div > div.pxAole > div.tvh9oe.BIB1wf > c-wiz > div.OUZ5W > div.zjoqD > div > div.v4dQwb > a > img').getAttribute('src')
        return src;
    })
    console.log(imgSrc)


来源:https://stackoverflow.com/questions/63924916/get-img-src-on-google-images-with-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!