Puppeteer:如何 select 基于文本的下拉选项?

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

在 Puppeteer 中,我们可以通过提供值作为参数来 select 下拉选项:

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

是否有 select 基于其文本而不是其值的选项的功能?

Puppeteer 中没有这样的方法API。但是你可以selectoption基于一个带有XPath的文本,然后提取这个元素的值,并将这个值传递给page.select()。这是一个完整的例子:

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

您可以使用page.evaluate() to find the option you would like to select by its text property. Then you can use the 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;
});

您可以使用 page.evaluate() 并直接转到您想要的元素。

await page.evaluate(() => {
    $("#idOfSelect option:contains('your-text')")[0].selected = true
})

虽然如果您的元素不存在,这将引发错误,因此您应该确保在 select 它之前该元素是否确实存在..

$$eval 可能比这些其他答案更清晰:

let optionValue = await page.$$eval('option', options => options.find(o => o.innerText === "foo")?.value)
await page.select('select#idOfSelect', optionValue);