简体   繁体   中英

Puppeteer - How to select an option from dropdown select within an optgroup

I'm trying to select an option from dropdown select which contains an optgroup.

    <select name="someName">
      <optgroup label="A">
        <option value="AC">AC</option>
        <option value="Abarth">Abarth</option>
        <option value="Acura">Acura</option>
        <option value="Aixam">Aixam</option>
        <option value="Alfa Romeo">Alfa Romeo</option>
        <option value="Alpina">Alpina</option>
       </optgroup>
       <optgroup label="B">
        <option value="Bentley">Bentley</option>
        <option value="Bugatti">Bugatti</option>
       </optgroup>
    </select>

How I can select an option from the select above regardless its optgroup?

If there's no a optgroup the Standart selecting is working

await page.select('select[name="someName"]', 'Alfa Romeo');

It works with and without optgroup element, page.select() does handle it for you.

For showcasing it, here's an example which selects different elements and waits 2 seconds between it. Watch it in browser!


var puppeteer = require('puppeteer')
const html = `
<select name="someName">
<optgroup label="A">
  <option value="AC">AC</option>
  <option value="Abarth">Abarth</option>
  <option value="Acura">Acura</option>
  <option value="Aixam">Aixam</option>
  <option value="Alfa Romeo">Alfa Romeo</option>
  <option value="Alpina">Alpina</option>
 </optgroup>
 <optgroup label="B">
  <option value="Bentley">Bentley</option>
  <option value="Bugatti">Bugatti</option>
 </optgroup>
</select>
`
// utility..
const wait = async (ms) => {
    return new Promise(res => {
        setTimeout(res, ms)
    })
}

const main = async() => {
    const browser = await puppeteer.launch({ headless: false })

    const page = await browser.newPage()

    await page.setContent(html)

    await page.select('select[name="someName"]', 'Alfa Romeo');

    await wait(2 * 1000)

    await page.select('select[name="someName"]', 'Alpina');

    await wait(2 * 1000)

    await page.select('select[name="someName"]', 'Bugatti');

    await wait(2 * 1000)

    await page.select('select[name="someName"]', 'Bentley');

    console.log('wating.. I am done.')
    await wait(5 * 1000)
    await browser.close()

}

main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM