puppeteer:根据外部函数中的文本设置选择的下拉选项

时间:2018-03-05 17:57:43

标签: node.js automated-tests google-chrome-devtools puppeteer

因为我没有找到puppeteer原生函数来设置基于文本选择的下拉选项,而不是基于值,我试着自己编写

async function setSelectName(page, selector, valText) {
   return await page.evaluate((data) => {
       console.log(JSON.stringify(data));

       let options = document.querySelectorAll(data.selector);
       console.log(JSON.stringify(options));

       let optionCount = options.length;

       for (let i = 0; i < optionCount; ++i) {
           if (options[i].text === data.valText) {
               console.log('match');
                document.querySelector(data.selector).value = options[i].value;
           }
       }

   }, {selector, valText})
}

不幸的是它不起作用,当我尝试在控制台中显示所选选项时,它会显示我:

  

{ “0”:{ “0”:{}, “1”:{}, “2”:{}, “3”:{}}}

了解发生了什么以及如何做到这一点?

3 个答案:

答案 0 :(得分:1)

这不是最直观的工作流程。这是一个抓取页面以获取name节点的select属性的Glitch示例。

https://glitch.com/edit/#!/puppeteer-queryselector-eval-example

server.js

const express = require('express'),
    app = express(),
    puppeteer = require('puppeteer');

app.use(express.static('public'));

app.get("/", async (request, response) => {
  try {
    const browser = await puppeteer.launch({
      args: ['--no-sandbox']
    });
    const page = await browser.newPage();
    await page.goto('https://sleet-dagger.glitch.me/cars.html');
    const selector = 'select';
    const name = await page.$eval(selector, node => node.name);
    response.send(name);
    await browser.close();
  } catch (error) {
    response.status(503).end(error.message);
  }
});

var listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});

cars.html

<!DOCTYPE html>
<html>
<body>

<select name="bingo">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

</body>
</html>

密钥是const name = await page.$eval(selector, node => node.name),它在页面上运行document.querySelector(selector),然后将节点传递给第二个参数中的回调函数。另见:

我认为这应该足以让你继续前进。祝你好运!

答案 1 :(得分:1)

async function selectOptionByText(page, seletctId, textWanted) {

   const optionWaned = (await page.$x(`//*[@id = "${seletctId}"]/option[text() = "${textWanted}"]`))[0];

   const opionValue = await (await optionWaned .getProperty('value')).jsonValue();

   await page.select(`#${seletctId}`', opionValue );
}

答案 2 :(得分:0)

您实际上并未选择文字,请尝试以下内容

let options = Array.from(document.querySelectorAll(data.selector)).map(option => option.innerText)