Puppeteer笔记(四):Puppeteer模拟键盘
Puppeteer系列
2、Puppeteer笔记(二):Puppeteer安装及实例Demo
3、Puppeteer笔记(三):Puppeteer获取元素及元素属性
4、Puppeteer笔记(四):Puppeteer模拟键盘
5、Puppeteer笔记(五):Puppeteer文件上传
6、Puppeteer笔记(六):Puppeteer切换frame操作
7、Puppeteer笔记(七):Puppeteer切换浏览器TAB页
8、Puppeteer笔记(八):Puppeteer执行自定义Javascript方法
一、Puppeteer模拟键盘
1、keyboard.down(key[,options])
2、keyboard.press(key[,options])
3、keyboard.type(text,options)
4、keyboard.up(key])
二、上手实例Demo
Puppeteer模拟键盘,功能测试:打开百度首页,输入"hello world!",删除world,并模拟键盘按下”A"。
const puppeteer = require('puppeteer'); async function keyboard() { //创建一个Browser浏览器实例,并设置相关参数
const browser = await puppeteer.launch({ headless: false, defaultViewport: null, args: ['--start-maximized'], ignoreDefaultArgs: ['--enable-automation'] }); //创建一个Page实例 const page = await browser.newPage();
//打开百度首页 await page.goto("https://www.baidu.com"); await page.$('#kw'); //键盘输入'Hello World!' await page.keyboard.type('Hello World!'); await page.waitFor(2000); //键盘按下鼠标左键 await page.keyboard.press('ArrowLeft'); //按住键盘shift await page.keyboard.down('Shift'); for (let i = 0; i < ' World'.length; i++) await page.keyboard.press('ArrowLeft'); await page.keyboard.up('Shift'); //键盘按住回车键盘 await page.keyboard.press('Backspace'); //紧接着模拟键盘按下大写的"A", await page.keyboard.down('Shift'); await page.keyboard.press('KeyA'); await page.keyboard.up('Shift'); //结果字符串最终为 'HelloA!' await page.waitFor(3000); //截图并保存至keyboad.png await page.screenshot({ path: 'keyboard.png' }); await browser.close(); } keyboard();