Reputation: 5611
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?
Upvotes: 15
Views: 29716
Reputation: 54992
$$eval is probably a bit cleaner than these other answers:
let optionValue = await page.$$eval('option', options => options.find(o => o.innerText === "foo")?.value)
await page.select('select#idOfSelect', optionValue);
Upvotes: 9
Reputation: 179
You can use page.evaluate() and go directly to the element you want.
await page.evaluate(() => {
$("#idOfSelect option:contains('your-text')")[0].selected = true
})
Though this will thrown an error if your element it's not present, so you should ensure if the element actually exists before you select it..
Upvotes: 5
Reputation: 29017
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;
});
Upvotes: 14
Reputation: 16049
There is no such method in Puppeteer API. But you can select option
based on a text with XPath, then extract the value of this element and pass this value to page.select()
. Here is a full example:
const puppeteer = require('puppeteer');
const html = `
<html>
<body>
<select id="selectId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</body>
</html>`;
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(`data:text/html,${html}`);
const option = (await page.$x(
'//*[@id = "selectId"]/option[text() = "Audi"]'
))[0];
const value = await (await option.getProperty('value')).jsonValue();
await page.select('#selectId', value);
await page.screenshot({ path: 'screenshot.png' });
await browser.close();
})();
Upvotes: 28