Select option by text, not by value with puppeteer

Target URL: http://www.supremenewyork.com/shop/jackets/uaxjeqvro/fm9kozqa6

Target Element: #s

Problem: Can’t select a value from the drop down. I’ve tried multiple things, only related question I could find on Stack Overflow was this,[How to select an option from dropdown select but none of these answers describe how to select the option via the text of the element rather than the value of the option.

Answer

This should work, tested with version 1.7.0 on https://try-puppeteer.appspot.com/

const browser = await puppeteer.launch();

const page = await browser.newPage();
await page.goto('http://www.supremenewyork.com/shop/jackets/uaxjeqvro/fm9kozqa6');

let $elemHandler = await page.$('#s');
let properties = await $elemHandler.getProperties();
for (const property of properties.values()) {
  const element = property.asElement();
  if (element){
    let hText = await element.getProperty("text");
    let text = await hText.jsonValue();
    if(text==="Large"){
       let hValue = await element.getProperty("value");
       let value = await hValue.jsonValue();
      await page.select("#s",value); // or use 58730
      console.log(`Selected ${text} which is value ${value}.`);
    }
  }
}
await browser.close();

Leave a Reply

Your email address will not be published. Required fields are marked *