Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  50] [ 7]  / answers: 1 / hits: 26062  / 6 Years ago, mon, march 5, 2018, 12:00:00

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?


More From » node.js

 Answers
7

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();
})();

[#55009] Thursday, March 1, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katianatasham

Total Points: 293
Total Questions: 110
Total Answers: 103

Location: Saint Helena
Member since Mon, Jun 28, 2021
3 Years ago
;