Home > Net >  How to get the text from a selected option (not value) with puppeteer
How to get the text from a selected option (not value) with puppeteer

Time:11-17

I have a select option like this:

<label>Choose One:</label>
<select id="choose1">
    <option value="val1">Value 1</option>
    <option value="val2">Value 2</option>
    <option value="val3">Value 3</option>
</select>

Then, in my project I can select the necessary option, in the case below, I selected the val2 value.

await page.select('#choose1', 'val2');  

So, I'm trying to get the text of val2 but in all the attempts the return is wrong.

I've tryed this, and it returned the textContent of the first option:

const element = await page.$('#choose1 option');
const selected = await (await element.getProperty('textContent')).jsonValue();

If I use await page.$('#choose1 option:selected'), I get an error that is not a valid selector.

Can anyone help me?

CodePudding user response:

You can use .find on the options to pick the one that matches a particular value, then extract its text content:

const puppeteer = require("puppeteer"); // ^19.0.0

const html = `
<select id="choose1">
  <option value="val1">Value 1</option>
  <option value="val2">Value 2</option>
  <option value="val3">Value 3</option>
</select>
`;

let browser;
(async () => {
  browser = await puppeteer.launch();
  const [page] = await browser.pages();
  await page.setContent(html);
  const targetVal = "val2";

  // not really necessary
  // await page.select("#choose1", targetVal); 

  const selectedText = await page.$$eval(
    "#choose1 option",
    (els, targetVal) =>
      els.find(el => el.value === targetVal).textContent,
    targetVal
  );
  console.log(selectedText); // => Value 2
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

CodePudding user response:

It is very simple without puppeteer, you can adapt it.

let optionText = '';
document
  .querySelectorAll('#choose1 option')
  .forEach(option => optionText = option.value === 'val2' && option.text)
  • Related