puppeteer返回在下拉列表中选择的值



如何从下拉列表中获取所选值(页面上显示的值(

<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

我认为最简单的方法是使用木偶师$eval。https://pptr.dev/#?product=Puppeteer&版本=v5.2&show=api-pagevalselect-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

您可以将目标改为选定。

document.querySelector('option[selected="selected"]').innerText

试试这个。。

尽管如评论中所述,如果你试图获得的元素比你给出的例子嵌套得更多;完整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)
})();

最新更新