Puppeteer:如何根据文本选择下拉选项?

Viv*_*ipo 7 javascript node.js google-chrome-devtools google-chrome-headless puppeteer

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

page.select('select#idOfSelect', 'optionValue'); 
Run Code Online (Sandbox Code Playgroud)

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

Eve*_*tss 18

Puppeteer API 中没有这样的方法。但是您可以option使用 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();
})();
Run Code Online (Sandbox Code Playgroud)


pgu*_*rio 9

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

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


Gra*_*ler 7

您可以使用page.evaluate()findoption,你想用它来选择text属性。然后您可以使用该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;
});
Run Code Online (Sandbox Code Playgroud)


小智 5

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

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

尽管如果您的元素不存在,这会引发错误,因此您应该在选择该元素之前确保该元素是否确实存在。