Select 'select' through Puppeteer

Asked

Viewed 481 times

1

I need to select a value within a <select>, but I’m not succeeding... I once did that same function of selecting a value in a <select> but this time I’m not getting to make that selection.

Follows the code:

await page.waitForSelector('#form-clientes\:contrato') //return is not a valid selector
await page.select('#form-clientes\:contrato', '0000000')

The field selector itself comes with this \:, the ID is #form-control:contrato

I also tried using page.evaluate(() => {}) but it didn’t work.

The error returned is always this

Error é: Error: Evaluation failed: DOMException: Failed to execute 'querySelector' on 'Document': '#form-clientes:contrato' is not a valid selector.
    at predicate (eval at waitForPredicatePageFunction (:2:21), <anonymous>:6:20)
    at eval (eval at waitForPredicatePageFunction (:2:21), <anonymous>:25:7)
    at pollMutation (__puppeteer_evaluation_script__:17:31)
    at waitForPredicatePageFunction (__puppeteer_evaluation_script__:9:18)
  • Use two bars on the selector '#form-clientes\\:contrato'

1 answer

1

You can use evaluate to make this process.

There is an extension of Chrome that gives you the value of the css selector, this in a faster way, the copy-css-selector it will add the Css Path field to your Devtools. after knowing the exact selector, you can make select this way:

await page.evaluate(() => {
      document.querySelector("input#form-clientes").value = 1;
}).catch(error => { console.log(error) });

can even take some value you want, for example:

var valorTeste = "nome";

await page.evaluate((valorTeste ) => {
      document.querySelector("input#form-clientes").value = valorTeste;
},valorTeste).catch(error => { console.log(error) });

in some cases the page does not recognize the change made with the evaluate, to make it work you need to make the change, one way I use a lot is this:

await page.evaluate(() => {
      $("input#form-clientes").trigger("change");
}).catch(error => { console.log(error) });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.