Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer: How to select a dropdown option based on its text?

In Puppeteer, we can select an option of a dropdown by providing the value as a parameter:

page.select('select#idOfSelect', 'optionValue'); 

Is there a function to select an option based on its text and not from its value?

like image 750
Pipo Avatar asked Mar 05 '18 17:03

Pipo


1 Answers

You can use page.evaluate() to find the option you would like to select by its text property. Then you can use the selected property to indicate that the option is currently selected:

await page.evaluate(() => {
  const example = document.querySelector('#example');
  const example_options = example.querySelectorAll('option');
  const selected_option = [...example_options].find(option => option.text === 'Hello, world!');

  selected_option.selected = true;
});
like image 74
Grant Miller Avatar answered Oct 19 '22 23:10

Grant Miller