Stickz
Stickz

Reputation: 37

How to reload and wait for an element to appear?

I tried searching for this answer but there doesn't seem to be an answer on the Internet. What I want to do is use node js to reload a page until it finds the element with the query I want. I will be using puppeteer for other parts of the program if that will help.

Ok, I used functions from both answers and came up with this, probably unoptimized code:

const puppeteer = require("puppeteer");

(async () => {
  try {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto("http://127.0.0.1:5500/main.html");
    await page.waitForSelector("#buy-button");
    console.log("worked");
  } catch (err) {
    console.log(`ERROR: ${err}`);
  }
})();  

                              

But what I don't know how to do is to reload the page, and keep reloading until the id I want is there. For example, keep reloading youtube until the video you want is there(unpractical example, but I think it gets the point across).

Upvotes: 2

Views: 3347

Answers (3)

SimonS
SimonS

Reputation: 936

Here's how I solved waiting for an element in puppeteer and reloading the page if it wasn't found;

async waitForSelectorWithReload(selector: string) {
    const MAX_TRIES = 5;
    let tries = 0;
    while (tries <= MAX_TRIES) {
      try {
        const element = await this.page.waitForSelector(selector, {
          timeout: 5000,
        });
        return element;
      } catch (error) {
        if (tries === MAX_TRIES) throw error;

        tries += 1;
        void this.page.reload();
        await this.page.waitForNavigation({ waitUntil: 'networkidle0' });
      }
    }
  }

And can be used as;

await waitForSelectorWithReload("input#name")

Upvotes: 2

Daniel
Daniel

Reputation: 1472

You can use "waitUntil: "networkidle2" to make sure the page is done loading. Obviously change the url, unless you are actually using evil.com

const puppeteer = require("puppeteer"); // include library
(async () =>{
  const browser = await puppeteer.launch(); // run browser
  const page = await browser.newPage(); // create new tab
  await page.goto(
    `http://www.evil.com`,
    {
      waitUntil: "networkidle2",
    }
  );
  // do your stuff here
  await browser.close();
})();

Upvotes: 1

Or Assayag
Or Assayag

Reputation: 6356

const puppeteer = require('puppeteer');

puppeteer.launch().then(async browser => {
  const page = await browser.newPage();
  page
    .waitForSelector('#myId')
    .then(() => console.log('got it'));
    browser.close();
});

Upvotes: 0

Related Questions