How to reload page in Puppeteer?

前端 未结 4 1087
孤独总比滥情好
孤独总比滥情好 2021-01-11 09:42

I would like to reload the page whenever the page doesn\'t load properly or encounters a problem. I tried page.reload() but it doesn\'t work.

fo         


        
相关标签:
4条回答
  • 2021-01-11 10:13

    So after the comments, the following line makes the error.

    ERROR Error: Error: failed to find element matching selector "div.det-name-int"
    

    bacause Puppetteer has a browser callback. When it finds the element and calls the callback, and if the element doesn't exist it throws an error.

    Also, the page is reloaded. You're not doing anything after that. If you want to fetch the image after that. Use

    await page.$eval('div.det-name-int', div => div.innerText.trim());
    

    after the reload. Or you can have a while loop to continuously check whether the element exists. If it doesn't then refresh page and check again. This ensures you will always have content.

    But if your content is dynamically generated and not part of the DOM at the moment you read the page, then your code becomes useless. You might need to add a timeout then search the dom for the element.

    0 讨论(0)
  • 2021-01-11 10:20

    I manage to solve it using a while loop.

    for (let appUrl of appUrls) {
        var count = i++;
    
        while(true){
            try{
    
                await page.goto(appUrl);
    
                const appName = await page.$eval('div.det-name-int', div => div.innerText.trim());
    
                console.log('\n' + count);
                console.log('Name: ' , appName);
    
                break;
    
                } catch(e){
                  console.log('\n' + count);
                  console.log('ERROR');
                  await page.reload(appUrl);
    
                  continue;
                }
    
    }
    
    0 讨论(0)
  • 2021-01-11 10:23

    You always can reload page via DOM, like this:

    await page.evaluate(() => {
       location.reload(true)
    })
    

    or here is a lot of ways how you can reload page with browser JS via DOM

    Also, you can navigate your puppeteer back and forward. Like this:

    await page.goBack();
    await page.goForward();
    
    0 讨论(0)
  • 2021-01-11 10:27

    This works for me:

    await page.reload({ waitUntil: ["networkidle0", "domcontentloaded"] });
    

    See Puppeteer docs for details: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagereloadoptions

    0 讨论(0)
提交回复
热议问题