这里只记录一些易忽略且重要的点。
无头及调试模式下全屏设置
调试模式
1 2 3 4 5 6 7
| const browser = await puppeteer.launch({ headless: false, defaultViewport: null, args: [ '--start-maximized', ], });
|
无头模式,此时再设置args参数为 --start-maximized
是无效的
1 2 3 4 5 6
| const browser = await puppeteer.launch({ headless: true, args: [ "--window-size=1920,1080", ], });
|
或者
1
| await page.setViewport({width: 1920, height: 1080});
|
设置文档下载路径及清除缓存
1 2 3 4 5 6 7
| const client = await page.target().createCDPSession(); await client.send("Network.clearBrowserCookies"); await client.send("Network.clearBrowserCache"); await client.send("Page.setDownloadBehavior", { behavior: "allow", downloadPath: targetDir, });
|
上传文件
1 2
| const fileChose = await page.waitForSelector('input[type="file"]'); await fileChose.uploadFile(sourcePath);
|
输入框输入
1
| await page.type('.search-box__input', 'text...');
|
等待选择器出现并点击
1 2 3
| const searchResultSelector = '.button'; await page.waitForSelector("searchResultSelector"); await page.click(searchResultSelector);
|
等待选择器出现并获取其内文本
1 2 3 4
| const textSelector = await page.waitForSelector( 'text/Customize and automate' ); const text = await textSelector.evaluate(el => el.textContent);
|