Search code examples
javascriptpuppeteerhtml-select

Puppeteer get all option's value


I would like to get an array all of the option's value, but I always get only the first option.

The HTML source:

<div class="select-wrapper control-container">
    <select name="type" id="product_finder_type" class="widget-input" data-name="type">
        <option class="placeholder">Select Vehicle Type</option>
        <option value="pc" >Passenger Car</option>
        <option value="truck" >Truck</option>
        <option value="conag" >Construction and Agriculture</option>
        <option value="bike" >Bike</option>
    </select>
</div>

My Code:

const tipusArray = await page.evaluate(() =>
    Array.from(
      document.querySelectorAll('#product_finder_type'),
      (element) =>
        element.textContent
    )
  );

console.log(tipusArray)

Result:

[ '\n\t\t\t\t\t\t\t\tSelect Vehicle Type\t\t\t\t\t\t\t' ]

How can I collect all of the options?


Solution

  • The main problem is in your selector:

    const tipusArray = await page.evaluate(() =>
        Array.from(document.querySelectorAll('#product_finder_type option')).map(element=>element.value)
      );
    
    console.log(tipusArray)
    

    Above code will give you array of all option values

    Provided all the data is static. In other words if the website is loading some data using js then you will have to wait until the website has completed all api calls then run the query.

    You can accomplish the above using :

    await page.waitForTimeout(4000)