sips
sips

Reputation: 11

How to find elements in puppeteer?

I'm having trouble finding the exact element 'closeIcon' Please take a look if you have time and let me know what you think.


const PAGEURL = "https://www.shoepalace.com/";

try {
    
(async () => {


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

    const page = await browser.newPage();  

    await page.goto(PAGEURL);
    
    page.waitForNavigation();
    
    const cancel = await page.waitForSelector('#cancelicon', {timeout: 60000});

    
    cancel.click();
    
    
    
})();
    
} catch (err){
    console.error(err);

}


function sleep(seconds) 
{
  var e = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= e) {}
}

Here is a ss of the page elements:

https://gyazo.com/f3ba9895dfb79f224119acfbdc7901bb

Here is the error in console:

https://gyazo.com/9a15f0e86f1c253182da89358f3de4b0

Upvotes: 1

Views: 1084

Answers (1)

F&#233;lix
F&#233;lix

Reputation: 154

The element you're looking for is located into an iframe.

Each of the iframe is a different frame of the page, you usually don't see it but for exmaple when you call :

page.waitForSelector('#cancelicon', {timeout: 60000});

In reality you call :

page.mainFrame().waitForSelector('#cancelicon', {timeout: 60000});

So you need to select the correct frame which ocntains your selector.

If it can help I coded this quick-and-dirty way to have the frame associated to the selector (-1 if nothing found, 0 for the main frame and a number for the corresponding frame) :

async function getFrameAssociatedToSelector(page, selector){
  if (selector !== ''){
    let querySelectoronPage = await page.$(selector);
    if(querySelectoronPage === null){
      for(var i=0;i<page.mainFrame().childFrames().length;i++){
        let querySelectoronFrame = await page.mainFrame().childFrames()[i].$(selector);
        if(querySelectoronFrame === null){
          continue;
        }else{
          return i+1;
        };
      };
      return -1;
    }else{
      return 0;
    }
  }else{
    return -1;
  };
};

You can then use it this way :

    if(stepFrame === 0){
      page.waitForSelector('#cancelicon', {timeout: 60000});
    }else{
      page.mainFrame().childFrames()[stepFrame-1].waitForSelector('#cancelicon', {timeout: 60000});
    };

Upvotes: 1

Related Questions