Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

javascript - Puppeteer Cannot read property getElementById of undefined

I'm trying to pass a value to the browser created by the puppeteer, but this error appears:

Cannot read property 'getElementById' of undefined

async function start() {
    const browser = await puppeteer.launch({
        headless : false
    });
    const page = await browser.newPage();
    await page.goto('https://www.google.com/recaptcha/api2/demo?invisible=true');

    await page.document.getElementById("g-recaptcha-response").innerHTML === response.text
    
    await Promise.all([
        page.click('#recaptcha-demo-submit'),
    ]);
}

The error is in this line:

await page.document.getElementById("g-recaptcha-response").innerHTML === response.text

what am I doing wrong?

Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can only use getElementById in the page context. Use page.evaluate, eg:

const html = await page.evaluate(() => {
    return document.getElementById("g-recaptcha-response").innerHTML;
});
console.log(html);

That'll take the the innerHTML of that element, send it back to Puppeteer, and log it in Node.

If you want to pass something to the page, you'll have to pass it to page.evaluate, eg

await page.evaluate((arg) => {
    return document.getElementById("g-recaptcha-response").value = arg;
}, '123');

That'll set the value of the textarea to 123.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...