浏览器管理
¥Browser management
通常,你可以通过在浏览器中启动 launching 或 connecting 来开始使用 Puppeteer。
¥Usually, you start working with Puppeteer by either launching launching or connecting to a browser.
启动浏览器
¥Launching a browser
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
const page = await browser.newPage();
// ...
关闭浏览器
¥Closing a browser
要正常关闭浏览器,请使用 browser.close()
方法:
¥To gracefully close the browser, you use the browser.close()
method:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
const page = await browser.newPage();
await browser.close();
浏览器上下文
¥Browser contexts
如果你需要隔离自动化任务,请使用 BrowserContexts。Cookie 和本地存储不在浏览器上下文之间共享。另外,你可以通过关闭上下文来关闭上下文中的所有页面。
¥If you need to isolate your automation tasks, use BrowserContexts. Cookies and local storage are not shared between browser contexts. Also, you can close all pages in the context by closing the context.
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
const context = await browser.createBrowserContext();
const page1 = await context.newPage();
const page2 = await context.newPage();
await context.close();
权限
¥Permissions
你还可以配置浏览器上下文的权限:
¥You can also configure permissions for a browser context:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
const context = browser.defaultBrowserContext();
await context.overridePermissions('https://html5demos.com', ['geolocation']);
连接到正在运行的浏览器
¥Connecting to a running browser
如果你在 Puppeteer 之外启动了浏览器,则可以使用 connect
方法连接到它。通常,你可以从浏览器输出中获取 WebSocket 端点 URL:
¥If you launched a browser outside of Puppeteer, you can connect to it using connect
method. Usually, you can grab a WebSocket endpoint URL from the browser output:
const browser = await puppeteer.connect({
browserWSEndpoint: 'ws://127.0.0.1:9222/...',
});
const page = await browser.newPage();
browser.disconnect();
与 browser.close()
不同,browser.disconnect()
不会关闭浏览器或关闭任何页面。
¥Unlike browser.close()
, browser.disconnect()
does not shut down the browser or close any pages.