How can I grab the selected value from a dropdown (the value that is shown on the page)
<div class="form"> <select name="stock" id="quantity_db" class="js_quantity_dropdown"> <option value="1" >1</option> <option value="2" >2</option> <option value="3" >3</option> <option value="4" >4</option> <option value="5" >5</option> <option value="6" selected="selected">6</option> </select>
I have the following code.
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({headless: false}) const page = await browser.newPage(); await page.goto('https://.....'); const option = await page.evaluate(()=> { document.getElementById("quantity_db").options[document.getElementById("quantity_db").selectedIndex].text; }); console.log('Selected option is:', option) })();
What I get when I run this is:
Selected option is: undefined
So that’s not working…
UPDATE: Since the html page is very long I’ve added it to a fiddle jsfiddle.net/cad231/c14mnp6z The id of the select item is of which I would like to obtain the value : #tst_quantity_dropdown
Advertisement
Answer
I think the easiest way is to use puppeteer $eval
. https://pptr.dev/#?product=Puppeteer&version=v5.2.1&show=api-pageevalselector-pagefunction-args-1
Select element by id and just ask for it’s value will give you the selected value in the dropdown.
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({headless: false}) const page = await browser.newPage(); await page.goto('https://afrekenen.bol.com/nl/winkelwagentje/direct-toevoegen?id=1001024332369558:2'); const option = await page.$eval("#tst_quantity_dropdown", node => node.value); console.log('Selected option is:', option) })();
Ouputs: Selected option is: 2