How to fill an input field using Puppeteer?

2020-05-18 04:39发布

问题:

I'm using Puppeteer for E2E test, and I am now trying to fill an input field with the code below:

await page.type('#email', 'test@example.com');

It worked, but I found the email address was typed into the field one character by one character as if a real human being was typing.

Is it possible to fill the input field with the email address all at one time?

回答1:

Just set value of input like this:

await page.$eval('#email', el => el.value = 'test@example.com');

Here is an example of using it on Wikipedia:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://en.wikipedia.org', {waitUntil: 'networkidle2'});

    await page.waitFor('input[name=search]');

    // await page.type('input[name=search]', 'Adenosine triphosphate');
    await page.$eval('input[name=search]', el => el.value = 'Adenosine triphosphate');

    await page.click('input[type="submit"]');
    await page.waitForSelector('#mw-content-text');
    const text = await page.evaluate(() => {
        const anchor = document.querySelector('#mw-content-text');
        return anchor.textContent;
    });
    console.log(text);
    await browser.close();
})();


回答2:

To extend the accepted answer above, you can use $eval with locally scoped variables too,

const myLocalValue = 'Adenosine triphosphate';    
await page.$eval('input[name=search]', (el, value) => el.value = value, myLocalValue);

This will take 'myLocalValue' from the local scope, and pass it into the browser scope as 'value'



回答3:

another way doing

await page.focus('#email')
await page.keyboard.type('test54')


回答4:

page.evaluate()

You can use page.evaluate() to assign the email string to the value attribute of the element:

await page.evaluate(() => {
  const email = document.querySelector('#email');
  email.value = 'test@example.com';
});