如何从下拉列表(页面上显示的值)中获取选定的值
<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>
我有以下代码。
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)
})();
运行此命令后得到的是:
Selected option is: undefined
那是行不通的...
更新:由于html页面很长,所以我已将其添加到小提琴jsfiddle.net/cad231/c14mnp6z选择项的ID是我想要获取的值:#tst_quantity_dropdown
答案 0 :(得分:1)
我认为最简单的方法是使用伪造者$eval
。 https://pptr.dev/#?product=Puppeteer&version=v5.2.1&show=api-pageevalselector-pagefunction-args-1
通过id选择元素,只需询问其值,即可在下拉列表中为您提供选定的值。
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)
})();
输入:Selected option is: 2
答案 1 :(得分:0)
您可以定位选定对象。
document.querySelector('option[selected="selected"]').innerText
答案 2 :(得分:0)
尝试一下。
尽管如注释中所述,如果要获取的元素比您给出的示例嵌套的多,那么我建议转到网页ans复制/从所需的元素粘贴“完整的JS路径”检查(在这种情况下为选项)
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(()=> {
//If this form is nested more than the code you provided then just go to the element in DevTools > right click > copy > full JS path.... This will give you the exact path the the form / form elements
var opts = document.querySelectorAll("#mainContent > div.shopping-cart > div > div > div.product__actions > div > div > div.product-actions__amount > div > form > fieldset > div.fluid-grid__item.h-relative > div > #tst_quantity_dropdown> option");
var selected;
//Check if each option has the "selected" attribute or not
opts.forEach(opt => {
if(opt.hasAttribute('selected')){
selected = opt.textContent;
}
});
return selected;
});
//Wait for result and log it outside of the evaluate function
let result = await option;
console.log(result)
})();