How to set value of select with node Puppeteer

限于喜欢 提交于 2019-12-07 06:47:45

问题


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.


回答1:


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

await page.select('select#example', 'carrot');



回答2:


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')


来源:https://stackoverflow.com/questions/45791930/how-to-set-value-of-select-with-node-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!