首页 > 解决方案 > 在 puppeteer 中处理禁用的选择选项

问题描述

我需要从 Puppeteer 的下拉列表中进行选择 - 该选项并不重要,但需要提交表单。问题是下拉菜单可能包含几个禁用的选项,我似乎无法排除这些。

这是在测试结账时将带有选项的商品添加到购物车。添加到购物车按钮被禁用,直到选择了正确的选项。

由于选项选择是动态的,并且每个产品都会发生变化,因此我无法知道哪些选项已启用且有库存。

我最初尝试选择第一项 selectedindex = 1,然后还尝试使用多种方法排除属性:

const option = (await page.$x(
    '//*[@id = "selectID"]/option[disabled=null]'
  ))[0];
const value = await (await option.getProperty('value')).jsonValue();
await page.select('#selectID', value);



<select name="Color" id="selectID" pseudoid="1" class="select" style="border: 1px solid lightgray; width: 190px;" selectedindex="0"><option value="-1">- Select -</option>

<option id="opt-0" outofstock="true" value="0" disabled="disabled" style="color: rgb(204, 204, 204);">Black[out of stock]</option>

<option id="opt-1" outofstock="true" value="1" disabled="disabled" style="color: rgb(204, 204, 204);">Blue[out of stock]</option>

<option id="opt-2" outofstock="true" value="2" disabled="disabled" style="color: rgb(204, 204, 204);">Red[out of stock]</option>

<option id="opt-3" outofstock="true" value="3" disabled="disabled" style="color: rgb(204, 204, 204);">Chocolate[out of stock]</option>

<option id="opt-4" value="4" style="color: black;">Green Camouflage</option>

<option id="opt-5" outofstock="true" value="5" disabled="disabled" style="color: rgb(204, 204, 204);">Pink Camouflage[out of stock]</option>

<option id="opt-6" value="6" style="color: black;">Arctic Blue Camouflage</option></select>

我想确定第一个有库存的选项。

我可以根据它具有的属性甚至文本/值来选择任何选项,但是如果该选项没有文本或属性,我似乎无法做到这一点。

标签: javascriptnode.jspuppeteer

解决方案


您可以使用以下evaluate功能解决该问题:

const select = await page.$("#selectID");
await page.evaluate(select => {
  for(let option of select.options)
  {
    if(!option.disabled) {
      option.selected = true;
    }
  }
}, select);
const value = await page.evaluate(select => select.value, select); 
console.log(value);

这将在浏览器端完成工作,减少往返。

如果您想在 Puppeteer 端选择该项目,您可以返回该选项:

const select = await page.$("#selectID");
const valueToSelect = await page.evaluate(select => {
  for(let option of select.options)
  {
    if(!option.disabled && option.id) {
      return option.value;
    }
  }
}, select);
await page.select("#selectID", valueToSelect);
const value = await page.evaluate(select => select.value, select); 
console.log(value);

推荐阅读