chicos, quiero hacer clic en un botón, aquí está mi código y el error que recibo:
await page.goto("http://website.com", {waitUntil: 'networkidle0'}); await page.click("[type=submit]") // ERROR Node is either not visible or not an HTMLElementIncluso intenté esperar al selector, aún los mismos resultados, intenté obtenerlo con Xpath, el mismo resultado
Sin embargo, cuando abro la consola en la misma pestaña, incluso en el propio controlador web, uso:
document.querySelector("[type=submit]") // It returns this: <button class="AnimatedForm__submitButton m-full-width" data-step="email" type="submit">Básicamente, el botón está ahí, pero mi titiritero no puede encontrarlo. No puedo ver que esté dentro de un iframe. Qué puede ser ?
He probado esto también:
await page.evaluate(selector=>{ return document.querySelector(['[type=submit]']).click();}) // ERROR TypeError: Cannot read property 'click' of undefinedAquí hay un ejemplo de un botón dentro de un iframe:
índice.html
<!DOCTYPE html> <html> <body> <iframe name="myFrame" src="frame.html"></iframe> </body> </html>marco.html
<!DOCTYPE html> <html> <body> <script> function myFunction() { document.querySelector('body').style.backgroundColor = 'red' } </script> <button class="AnimatedForm__submitButton m-full-width" data-step="email" type="submit" onclick="myFunction()"> Michelle Branch - Spirit Room </button> </body> </html> Si ejecuta document.querySelector('[type=submit]') en el navegador, devolverá el botón correctamente.
Pero, ¿por qué no funcionará en titiritero entonces?
La página significa el DOM de index.html . El titiritero solo puede alcanzar elementos dentro de su DOM normal.
const page = await browser.newPage() Pero no el DOM dentro del iframe . Será el alcance del DOM de frame.html , podemos obtenerlo con page.frames() así (por ejemplo, por su atributo de name ):
const frame = page.frames().find((frame) => frame.name() === 'myFrame')Entonces podemos comunicarnos con el botón interno también. P.ej:
guión.js
const puppeteer = require('puppeteer') ;(async () => { const browser = await puppeteer.launch({ headless: false }) const page = await browser.newPage() await page.goto('.../index.html') // await page.click('[type=submit]') // it doesn't find the element ❌ const frame = page.frames().find((frame) => frame.name() === 'myFrame') await frame.click('[type=submit]') // it finds the element ✅ // await browser.close() })()