Javascript 如何使用 Puppeteer 填充输入字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47966510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fill an input field using Puppeteer?
提问by choasia
I'm using Puppeteerfor E2E test, and I am now trying to fill an input field with the code below:
我正在使用Puppeteer进行 E2E 测试,现在我正在尝试使用以下代码填充输入字段:
await page.type('#email', '[email protected]');
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?
是否可以一次用电子邮件地址填写输入字段?
回答by Everettss
Just set value of input like this:
只需像这样设置输入值:
await page.$eval('#email', el => el.value = '[email protected]');
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();
})();
回答by Andrew
To extend the accepted answer above, you can use $eval with locally scoped variables too,
要扩展上面接受的答案,您也可以将 $eval 与局部范围的变量一起使用,
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'
这将从本地范围中获取 'myLocalValue',并将其作为 'value' 传递到浏览器范围中
回答by Sarath Ak
another way doing
另一种方式做
await page.focus('#email')
await page.keyboard.type('test54')
回答by Grant Miller
page.evaluate()
page.evaluate()
You can use page.evaluate()to assign the email string to the valueattribute of the element:
您可以使用page.evaluate()将电子邮件字符串分配给value元素的属性:
await page.evaluate(() => {
const email = document.querySelector('#email');
email.value = '[email protected]';
});

