文档
main.js
const pptr = require('puppeteer');
const gotoUrl = 'http://127.0.0.1:5500/index.html';
(async () => {
const browser = await pptr.launch({
headless: false,
slowMo: 250,
});
const page = await browser.newPage();
page.on('console', msg => {
console.log(msg.text());
});
await page.goto(gotoUrl);
await page.focus('input[type=text]');
// 要输入到焦点元素中的文本
await page.keyboard.type('Hello World!');
// 按下的键名, 比如 ArrowLeft
await page.keyboard.press('ArrowLeft');
// 按下之后不释放
await page.keyboard.down('Shift');
// 循环按了5次ArrowLeft
for (let i = 0; i < ' World'.length; i++)
await page.keyboard.press('ArrowLeft');
// 释放按键
await page.keyboard.up('Shift');
// 按下删除键
await page.keyboard.press('Backspace');
await page.keyboard.type('ajanuw');
for (let i = 0; i < 'ajanuw'.length; i++)
await page.keyboard.press('ArrowLeft');
await page.keyboard.type(' ');
await page.keyboard.down('Shift');
await page.keyboard.press('ArrowRight');
await page.keyboard.type('A');
await page.keyboard.up('Shift');
const value = await page.$eval('input[type=text]', e => e.value);
console.log(value); // Hello Ajanuw!
await browser.close();
})();
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<input type="text" />
</body>
</html>