现在位置: 首页 > Playwright 教程 > 正文

Playwright 核心类 API

本附录列出 Playwright 核心类的常用 API,供快速查阅。


Playwright 类

Playwright 是 Playwright Library 的入口对象。

方法/属性说明
playwright.chromium返回 Chromium 的 BrowserType 对象
playwright.firefox返回 Firefox 的 BrowserType 对象
playwright.webkit返回 WebKit 的 BrowserType 对象
playwright.request返回 APIRequest 对象
playwright.selectors返回 Selectors 对象

BrowserType 类

BrowserType 用于启动和连接到浏览器。

方法说明
browserType.launch(options?)启动浏览器实例
browserType.launchPersistentContext(userDataDir, options?)启动持久化 Context(使用本地用户数据目录)
browserType.connect(url, options?)连接到一个已运行的浏览器
browserType.connectOverCDP(url, options?)通过 CDP 协议连接到已运行的浏览器
browserType.executablePath()返回浏览器可执行文件路径
browserType.name()返回浏览器名称

Browser 类

Browser 代表一个浏览器实例。

方法/属性说明
browser.newContext(options?)创建新的 BrowserContext
browser.newPage(options?)在新 Context 中创建新 Page
browser.contexts()返回所有 Context 的列表
browser.close()关闭浏览器及所有页面
browser.browserType()返回对应的 BrowserType
browser.version()返回浏览器版本
browser.isConnected()是否已连接

BrowserContext 类

BrowserContext 代表一个独立的浏览器上下文。

方法说明
context.newPage()创建新页面
context.pages()返回所有打开的页面
context.close()关闭 Context
context.cookies(urls?)获取 Cookie
context.addCookies(cookies)添加 Cookie
context.clearCookies()清除所有 Cookie
context.storageState(options?)获取当前存储状态(用于认证复用)
context.grantPermissions(permissions)授予权限
context.clearPermissions()清除权限
context.setGeolocation(geolocation)设置地理位置
context.setExtraHTTPHeaders(headers)设置额外 HTTP 头
context.route(url, handler)拦截网络请求
context.unroute(url, handler?)取消拦截
context.exposeFunction(name, fn)向页面暴露函数
context.exposeBinding(name, callback)向页面暴露绑定

BrowserServer 类

BrowserServer 代表通过 launchServer() 启动的浏览器进程。

方法说明
browserServer.wsEndpoint()返回 WebSocket 端点 URL(用于远程连接)
browserServer.close()关闭服务器和浏览器
browserServer.kill()强制终止浏览器进程