Playwriter深度指南:如何让AI助手真正掌控你的浏览器 Playwriter深度指南如何让AI助手真正掌控你的浏览器【免费下载链接】playwriterChrome extension CLI to let agents control your browser. Runs Playwright snippets in a stateful sandbox. Available as CLI or MCP项目地址: https://gitcode.com/gh_mirrors/pl/playwriter你是否厌倦了那些只能在沙箱中运行的浏览器自动化工具是否曾因为每次都要重新登录网站而感到沮丧Playwriter为你带来了全新的解决方案——一个真正理解开发者需求的浏览器自动化MCP工具。它不仅让你现有的浏览器会话变得可编程还保留了所有登录状态、扩展插件和个人设置让AI助手能够像真人一样操作你的浏览器。Playwriter通过Chrome扩展运行提供完整的CDPChrome DevTools Protocol功能无上下文膨胀且性能强大。与传统的浏览器自动化工具不同Playwriter直接连接到你的实际浏览器实例这意味着你的所有Cookie、本地存储、扩展插件都保持原样。这种设计理念让自动化变得更加自然和高效。 为什么选择Playwriter而不是其他工具在浏览器自动化领域开发者面临多种选择但每种都有其局限性。传统的Playwright MCP会启动一个全新的Chrome实例这意味着你需要重新登录所有网站无法使用已安装的扩展而且很容易被反机器人系统检测到。BrowserMCP虽然提供了专门的工具集但API受限且上下文使用效率低下。Playwriter采用了截然不同的方法。它通过一个简单的Chrome扩展连接到你的现有浏览器让你可以保持现有会话所有登录状态、Cookie和本地存储都保持不变使用现有扩展广告拦截器、密码管理器等扩展继续工作避免机器人检测因为使用的是真实的用户浏览器会话减少内存占用无需启动第二个Chrome实例这张图片展示了Playwriter的核心价值主张通过浏览器扩展运行提供完整的CDP功能无上下文膨胀性能强大。这正是现代开发者需要的自动化解决方案。 快速上手三种安装方式全局安装推荐对于大多数用户来说全局安装是最方便的选择npm install -g playwriterlatest安装完成后你就可以在命令行中直接使用playwriter命令了。使用npx临时运行如果你不想全局安装或者只是想快速尝试一下可以使用npxnpx playwriterlatest session new使用bunx运行如果你使用Bun作为包管理器bunx playwriterlatest session new首次使用时建议加上latest标志以确保使用最新版本。 核心概念会话管理与状态隔离Playwriter的会话系统是其强大功能的基础。每个会话都在独立的沙箱中运行拥有自己的state对象。这种设计让你可以分离不同任务或代理的状态每个会话都有自己的存储空间在多次执行调用之间持久化数据页面、变量等都可以保存在state中避免多个代理同时使用时的干扰每个代理使用不同的会话ID创建和管理会话# 创建新会话 playwriter session new # 输出类似: 1 # 列出所有活动会话 playwriter session list # ID State Keys # -------------- # 1 myPage, userData # 2 - # 重置会话当浏览器连接不稳定时 playwriter session reset sessionId最佳实践始终使用自己的会话并通过-s id参数传递给所有命令。使用相同的会话可以在多次调用之间保持状态而使用不同的会话则会获得全新的状态。 执行代码Playwriter的核心能力执行JavaScript代码是Playwriter最强大的功能。通过命令行你可以控制浏览器执行各种复杂的自动化任务playwriter -s 1 -e code其中-s指定会话ID必需-e后面跟着要执行的JavaScript代码。实际应用示例导航到网页并获取信息playwriter -s 1 -e state.page await context.newPage(); await state.page.goto(https://example.com) playwriter -s 1 -e console.log(页面标题:, await state.page.title()) playwriter -s 1 -e console.log(当前URL:, state.page.url())与页面元素交互# 点击按钮 playwriter -s 1 -e await state.page.click(button) # 填写表单 playwriter -s 1 -e await state.page.fill(#email, userexample.com) # 选择下拉选项 playwriter -s 1 -e await state.page.selectOption(#country, US)截取屏幕截图playwriter -s 1 -e await state.page.screenshot({ path: /absolute/path/to/screenshot.png, scale: css })这张截图展示了Playwriter在实际使用中的界面浏览器地址栏显示playwriter.dev这是Playwriter的官方网站入口。代码引用技巧正确处理引号始终使用单引号包裹-e代码以防止bash解释$、反引号等特殊字符playwriter -s 1 -e await state.page.locator([id_r_a_]).click()执行多行代码对于复杂的多行代码使用heredoc语法playwriter -s 1 -e $(cat EOF const links await state.page.$$eval(a, els els.map(e e.href)); console.log(找到, links.length, 个链接); const price text.match(/\$[\d.]/); EOF )️ 高级配置优化你的工作流程优化Chrome启动参数为了获得更好的体验可以在启动Chrome时添加一些优化参数# macOS open -a Google Chrome --args --profile-directoryDefault --allowlisted-extension-idjfeammnjpkecdekppnclgkkffahnhfhe --auto-accept-this-tab-capture # Linux google-chrome --profile-directoryDefault --allowlisted-extension-idjfeammnjpkecdekppnclgkkffahnhfhe --auto-accept-this-tab-capture # Windows start chrome.exe --profile-directoryDefault --allowlisted-extension-idjfeammnjpkecdekppnclgkkffahnhfhe --auto-accept-this-tab-capture这些参数可以自动接受标签捕获无需手动点击扩展图标。配置本地MCP服务器如果你需要测试本地修改的MCP服务器可以在MCP客户端配置中添加{ mcpServers: { playwriter: { command: tsx, args: [/path/to/playwriter/playwriter/src/mcp.ts] } } }确保你已全局安装tsxpnpm i -g tsx 调试技巧解决常见问题查看日志文件Playwriter会生成详细的日志文件帮助你诊断问题playwriter logfile # 打印日志文件路径 # 通常路径: ~/.playwriter/relay-server.log日志文件包含来自扩展、MCP和WebSocket服务器的日志还有一个单独的CDP JSONL日志记录所有CDP命令/响应和事件。分析CDP流量使用jq工具分析CDP流量jq -r .direction \t (.message.method // response) ~/.playwriter/cdp.jsonl | uniq -c常见问题及解决方法扩展未连接如果收到extension is not connected错误请确保Chrome浏览器已打开Playwriter扩展已安装并启用在目标标签上点击了Playwriter扩展图标页面内容未加载即使goto()完成动态内容可能仍未加载await state.page.goto(https://example.com) await state.page.waitForSelector(article, { timeout: 10000 }) // 或使用waitForPageLoad工具 await waitForPageLoad({ page: state.page, timeout: 5000 }) 最佳实践编写高效的自动化脚本初始化页面在任务开始时始终初始化state.pagestate.page context.pages().find((p) p.url() about:blank) ?? (await context.newPage()) await state.page.goto(https://example.com)观察-行动-观察模式每个浏览器交互都应遵循观察-行动-观察模式打开页面并观察初始状态执行一个操作再次观察以验证操作效果// 步骤1: 导航 观察 state.page context.pages().find((p) p.url() about:blank) ?? (await context.newPage()) await state.page.goto(https://example.com, { waitUntil: domcontentloaded }) console.log(URL:, state.page.url()) await snapshot({ page: state.page }).then(console.log) // 步骤2: 行动 观察 await state.page.locator(button:has-text(Submit)).click() console.log(URL:, state.page.url()) await snapshot({ page: state.page }).then(console.log)使用快照进行页面分析优先使用snapshot()进行页面分析它提供文本化的页面结构比截图更高效await snapshot({ page: state.page, search: /expected text/i })只有在需要视觉布局信息时才使用截图。处理常见页面障碍大多数网站会显示各种弹窗和障碍如Cookie提示、登录墙等。导航后立即检查并处理这些障碍await waitForPageLoad({ page: state.page, timeout: 5000 }) const snap await snapshot({ page: state.page, search: /cookie|consent|accept|reject|decline|allow|age|verify|login|sign.in/i, }) console.log(snap) // 根据快照结果处理障碍 // await state.page.locator(button:has-text(Accept)).click(); 实用工具函数Playwriter提供了一系列强大的工具函数让你的自动化脚本更加高效获取清理后的HTMLconst html await getCleanHTML({ locator: state.page.locator(body) }) const html await getCleanHTML({ locator: state.page, search: /button/i }) const fullHtml await getCleanHTML({ locator: state.page, showDiffSinceLastCall: false })提取页面内容为Markdownconst content await getPageMarkdown({ page: state.page, showDiffSinceLastCall: false }) const matches await getPageMarkdown({ page: state.page, search: /API/i })智能页面加载检测const result await waitForPageLoad({ page: state.page, timeout: 5000 }) // 返回: { success, readyState, pendingRequests, waitTimeMs, timedOut }屏幕录制功能// 开始录制 await recording.start({ page: state.page, outputPath: /absolute/path/to/recording.mp4, frameRate: 30, audio: false, videoBitsPerSecond: 2500000, aspectRatio: { width: 16, height: 9 }, maxDurationMs: 15 * 60 * 1000, }) // 录制过程中可以正常导航 await state.page.click(a) await state.page.waitForLoadState(domcontentloaded) // 停止录制 state.recordingResult await recording.stop({ page: state.page }) 处理复杂场景网络请求拦截对于数据抓取或API反向工程拦截网络请求比解析DOM更高效state.requests [] state.responses [] state.page.on(request, (req) { if (req.url().includes(/api/)) state.requests.push({ url: req.url(), method: req.method(), headers: req.headers() }) }) state.page.on(response, async (res) { if (res.url().includes(/api/)) { try { state.responses.push({ url: res.url(), status: res.status(), body: await res.json() }) } catch {} } })处理iframe// 使用frameLocator进行链式操作 const frame state.page.frameLocator(#my-iframe) await frame.locator(button).click() // 使用contentFrame获取Frame对象用于snapshot const frame2 await state.page.locator(iframe).contentFrame() await snapshot({ frame: frame2 })处理弹窗对话框state.page.on(dialog, async (dialog) { console.log(dialog.message()) await dialog.accept() }) await state.page.click(button.trigger-alert) 避免常见错误1. 不验证操作是否成功await state.page.keyboard.type(my text) await snapshot({ page: state.page, search: /my text/ })2. 使用过时的定位器await snapshot({ page: state.page, showDiffSinceLastCall: true }) // 现在使用这个输出中的新定位器3. 对JS渲染的网站不使用Playwriter不要浪费时间尝试webfetch、curl或解析来自JS渲染站点的原始HTML。对于SPA如Instagram、Twitter、Facebook等直接使用Playwriterstate.page context.pages().find((p) p.url() about:blank) ?? (await context.newPage()) await state.page.goto(https://www.instagram.com/p/ABC123/, { waitUntil: domcontentloaded }) await waitForPageLoad({ page: state.page, timeout: 8000 }) await snapshot({ page: state.page, search: /cookie|consent|accept/i }).then(console.log) 总结开始你的Playwriter之旅Playwriter不仅仅是一个浏览器自动化工具它是一个完整的生态系统让AI助手能够真正理解并操作你的浏览器。通过直接连接到你的现有Chrome实例它保留了所有个人设置和登录状态使得自动化变得更加自然和高效。无论你是需要自动化日常任务、进行网页测试、数据抓取还是构建复杂的自动化工作流Playwriter都能提供强大的支持。它的会话隔离机制、丰富的工具函数和直观的API设计使得编写和维护自动化脚本变得异常简单。记住Playwriter的核心优势在于它的无干扰设计——它使用你现有的浏览器而不是创建一个新的、干净的实例。这意味着你可以利用已经登录的所有服务使用已经安装的所有扩展并且避免被反机器人系统检测到。现在就开始使用Playwriter体验真正的浏览器自动化吧从简单的导航和点击开始逐步探索更复杂的功能你会发现它能够极大地提升你的工作效率和自动化能力。【免费下载链接】playwriterChrome extension CLI to let agents control your browser. Runs Playwright snippets in a stateful sandbox. Available as CLI or MCP项目地址: https://gitcode.com/gh_mirrors/pl/playwriter创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考