playwright get all options value in a multiple select

Viewed 1020

I have this Select:

<select size="4" name="Select1" multiple="multiple" id="Select1">
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
    <option value="5">E</option>
    <option value="6">F</option>
 </select>

how can I get all the options value using playwright hopefully an example using C#

2 Answers

In node.js to get all the select options you can use:

const options = await page.$$eval('#Select1 > option', (els) => {
  return els.map(option => option.textContent)
})
console.log(options);

The equivalent for page.$$eval in .Net is Page.QuerySelectorAllAsync(selector).

You can check the documentation here:

https://playwright.dev/dotnet/docs/api/class-page#page-query-selector-all

Something along the lines of:

string[] values = (await Page.QuerySelectorAllAsync("#Select1 > option"))
    .Select(async option => await option.GetAttributeAsync("value"))
    .ToArray();
Related