$$。eval之后的操纵up点击功能

时间:2020-08-16 07:19:35

标签: javascript puppeteer chromium

我想下载使用Puppeteer在Google上搜索的图像。但是,单击图像按钮后,$.eval下面的功能不起作用。它说failed to find element matching selector div[jsname="I4bIT"] 。我想知道是否使用$$.eval单击某些内容来更改页面实例?预先非常感谢。

async function findAndDownloadImage(page, elem = 'hello') {
    try {
        await page.goto(`https://www.google.com/search?q=${elem}+expression`);

        await page.$$eval('.HF9Klc.iJddsb', elem => elem[1].click()); //click picture button

        await page.$eval('div[jsname="I4bIT"]', clickAction); //click tool button
        await page.$eval('div[aria-label="大小"]', clickAction); //click sizeButton 
        await page.$eval('a[aria-label="大"]', clickAction); //click largeOption 

        
        await page.$eval('.rg_i.Q4LuWd', clickAction); //click 1st image

    } catch (e) {
        console.log(e)
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在第一次单击后等待,直到图像搜索选项卡的元素加载到DOM中。可以使用page.waitForSelector

await page.$$eval('.HF9Klc.iJddsb', elem => elem[1].click()); //click picture button
await page.waitForSelector('div[jsname="I4bIT"]'); //wait for image-search tab loaded v1
await page.$eval('div[jsname="I4bIT"]', clickAction); //click tool button
...

...或page.waitForNavigation

await page.$$eval('.HF9Klc.iJddsb', elem => elem[1].click()); //click picture button
await page.waitForNavigation(); //wait for image-search tab loaded v2
await page.$eval('div[jsname="I4bIT"]', clickAction); //click tool button
...