Checking a radio button with Puppeteer
Overview
This is a memo on how to check a radio button using the scraping tool Puppeteer.
Example
Suppose we have the following radio button group.
<input type="radio" name="maker" value="1"> クリスタル映像 <input type="radio" name="maker" value="2"> ポセイドン企画
Answer
If you want to select クリスタル映像, do the following.
Use page.evaluate so that the result of operating inside the browser is returned.
Since this runs inside the browser, you can use document.querySelector.
There, we set `checked = true`.
const selectedRadioSelector = `input[type="radio"][value="1"]` await page.evaluate( s => (document.querySelector(s).checked = true), selectedRadioSelector )
Failed attempts
The click-based approaches all failed across the board.
I found an article saying it succeeds if you `page.WaitFor`, but in my own environment, puppeteer (version=1.19.0), it still failed.
- page.click
const selectedRadioSelector = `input[type="radio"][value="1"]` page.click(selectedRadioSelector)
- Grab the radio element and click
r = page.$(selectedRadioSelector) r.click()
- document.querySelector().click()
const selectedRadioSelector = `input[type="radio"][value="1"]` await page.evaluate( s => (document.querySelector(s).click()), selectedRadioSelector )
Going further
Suppose we have the following radio button group.
Compared to the one above, a label tag has been added.
<input type="radio" id="group1" name="maker" value="1"> <label for="group1">クリスタル映像</label> <input type="radio" id="group2" name="maker" value="2"> <label for="group1">ポセイドン企画</label>
Let's check the one whose label matches a regular expression.
- Check the one whose label contains the text "映像"
const regex = "映像" const regexpLabel = new RegExp(regex, 'g') const r = await page.$$('input[type="radio"]') label: for (const i in r) { // the id property of the radio button const id = await (await r[i].getProperty('id')).jsonValue() // the value property of the radio button const value = await (await r[i].getProperty('value')).jsonValue() // get the label's textContent (gets "クリスタル映像", "ポセイドン企画") const label = await page.$(`label[for="${id}"]`) const labelContent = await (await label.getProperty( 'textContent' )).jsonValue() // true if the label's textContent contains "映像" if (labelContent.match(regexpLabel)) { const selectedRadioSelector = `input[type="radio"][value="${value}"]` await page.evaluate( s => (document.querySelector(s).checked = true), selectedRadioSelector ) // the radio button has been checked, so finish processing break label } }
Summary
This was a very easy spot to get stuck on, so I left it here as a memo.
I hope it helps.

- 作者: 佐藤歩,加藤賢一,原一成,加藤圭佑,大塚健司,磯部有司,村田賢太,末永恭正,久保田祐史,吉川竜太,牧大輔,ytnobody(わいとん),前田雅央,浜田真成,竹馬光太郎,池田拓司,はまちや2,竹原,原田裕介,西立野翔磨,田中孝明
- 出版社/メーカー: 技術評論社
- 発売日: 2019/02/23
- メディア: 単行本
- この商品を含むブログを見る
Checking a radio button with Puppeteer
