Home > Software engineering >  How to click a list item with Puppeteer?
How to click a list item with Puppeteer?

Time:10-30

I'm new to puppeteer and I'm trying to click on a selector from a dropdown menu enter image description here

  • when I use DevTools, no element is returned for .mat-option ng-star-inserted mat-active selector, but I can find the desired element with #mat-option-0 selector, or I can use the longer version, but have to use a dot (.) before each class and delete spaces between them like so .mat-option.ng-star-inserted.mat-active, you can see a CSS reference enter image description here

    I got there with this script:

    const puppeteer = require('puppeteer');
    
    (async () => {
      const browser = await puppeteer.launch({ headless: false });
      const page = await browser.newPage();
      await page.goto('https://www.game.co.uk/en/-2640058?cm_sp=NintendoFormatHub-_-Accessories-_-espot-_-PikaCase');
      await console.log('Users navigated to site :)');
      await page.waitForSelector('.cookiePolicy_inner--actions');
      await page.click('.cookiePolicy_inner--actions');
      await page.waitForSelector('.addToBasket');
      await page.click('.addToBasket');
      await page.waitForSelector('.secure-checkout');
      await page.click('.secure-checkout');
      await page.waitForSelector('.cta-large');
      await page.click('.cta-large');
      await page.goto('https://checkout.game.co.uk/contact');
      await page.waitForSelector('.mat-form-field-infix');
      await page.click('.mat-form-field-infix');
      await page.waitForSelector('#mat-option-0');
      await page.click('#mat-option-0');
    })();
    

    However, this is still not ideal because:

    • you handle the cookie bar with clicks, try to find a way without clicking; perhaps injecting a cookie that disables the cookie bar (if possible)
    • the code is one big piece that is perhaps ok for now and this example but might become unmaintainable if you keep adding lines to it; try to reuse code in functions and methods
  • Related