7

I am trying to do some automation with the rather new GoogleChrome/puppeteer library, but I cannot figure out how to set a value in a select field.

Here is my (simplified) function to set the value of a text input:

async function setInputVal(sel, text) {
    await page.focus(sel)        
    page.press('Backspace')
    page.type(text)
}

await setInputVal('input.searchjob', task.id)

I cant figure out how to do the same for a select field.

I have tried to set the focus, insert script and execute but I cannot get it working.

danday74
  • 52,471
  • 49
  • 232
  • 283
BrendanMullins
  • 587
  • 3
  • 18
  • linked - [select an option from dropdown select](https://stackoverflow.com/q/45864516/104380) – vsync Aug 20 '18 at 09:49
  • Just as a follow-up: puppeteer does have a [first-class API](https://github.com/GoogleChrome/puppeteer/blob/v1.4.0/docs/api.md#pageselectselector-values) for this now. – browserless May 30 '18 at 07:28

2 Answers2

12

I found a solution myself:

async function setSelectVal(sel, val) {
    page.evaluate((data) => {
        return document.querySelector(data.sel).value = data.val
    }, {sel, val})
}

await setSelectVal('#select_id', 'newValue')
BrendanMullins
  • 587
  • 3
  • 18
3

You can use page.select() to select an option:

await page.select('select#example', 'carrot');
Grant Miller
  • 27,532
  • 16
  • 147
  • 165