使用说明
剧作家MCP服务器
一个最小、强大的Playwright MCP(模型上下文协议)服务器,通过一个简单的API展示核心浏览器自动化功能。
特征
- 浏览器上下文管理:持久浏览器上下文(无头或有头,可配置)
- 多页支持:处理多个选项卡/窗口,在页面之间切换,管理弹出窗口
- 导航:打开URL、重新加载、返回/前进
- DOM交互:使用Playwright选择器单击、键入、填充、选择、悬停、滚动
- 元素发现:使用CSS、XPath、角色、文本和其他Playwright定位器查询元素
- 快照:获取HTML、辅助功能快照、屏幕截图和PDF
- 令牌感知输出:可配置的上限将元素查询和可访问性快照保持在安全大小内,以供LLM使用
- 溢出工件:大型响应会自动修剪,默认情况下会在约2小时后自动清理,并包括预览和文件引用,您可以通过工件读取器工具重新打开它们
- 二进制友好默认值:截图、PDF和其他大blob作为元数据预览的工件存储,因此LLM可以控制上下文大小
- 脚本评估:在页面上下文中运行JavaScript
- 网络监控:捕获并分析所有网络请求和响应
- 网络侦听:阻止、修改或模拟网络请求
- Cookie管理:获取、设置和清除浏览器Cookie
- 存储访问:管理本地存储和会话存储数据
- 标头和用户代理:自定义请求标头和浏览器标识
- 原始输出:所有输出都是未经后期处理的原始剧作家结果
安装
从GitHub快速安装
# Install directly from GitHub
pip install git+https://github.com/alexrwilliam/playwright-mcp-server.git
# Install Playwright browsers
playwright install
为了发展
# Clone the repository
git clone https://github.com/alexrwilliam/playwright-mcp-server.git
cd playwright-mcp-server
# Install in development mode
pip install -e .
# Install browsers
playwright install
用法
运行服务器
安装后,您可以在任何地方使用它:
# Run with stdio transport (for MCP clients)
playwright-mcp stdio
# Run with HTTP transport
playwright-mcp http --port 8000
# Run in headed mode (default launch mode is headless)
playwright-mcp stdio --headed
命令行用法
# Run the MCP server
playwright-mcp stdio
# Run with visible browser
playwright-mcp stdio --headed
# Run HTTP server
playwright-mcp http --port 8000
# Use different browsers
playwright-mcp stdio --browser firefox
playwright-mcp stdio --browser webkit
# Chrome channel is the default for Chromium sessions.
# If Chrome isn't installed, the server falls back to bundled Chromium.
playwright-mcp stdio
# Use real Chrome with your profile (cookies, extensions, history)
playwright-mcp stdio --channel chrome --user-data-dir "/Users/you/Library/Application Support/Google/Chrome"
# Attach to an already-running real Chrome/Edge over CDP (useful when blocked/captcha-heavy)
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=1234 --user-data-dir=/tmp/pwmcp_cdp_profile
playwright-mcp stdio --cdp-endpoint
# Force a fresh context instead of reusing the first existing CDP context
playwright-mcp stdio --cdp-endpoint --no-cdp-use-existing-context
# Adjust response budgets (defaults: 4k inline, 400-char previews)
playwright-mcp stdio --max-response-chars 6000 --preview-chars 600
# Choose where overflow artifacts are written
playwright-mcp stdio --artifact-dir /tmp/playwright-artifacts
# Control how much each artifact chunk returns inline
playwright-mcp stdio --artifact-chunk-size 8192
# Other Chrome channels
playwright-mcp stdio --channel chrome-beta
playwright-mcp stdio --channel chrome-dev
隐形和指纹控制
- 默认基线(无标志):Chromium启动时带有Chrome频道偏好,条带
--enable-automation,并添加--disable-blink-features=AutomationControlled以更好地匹配Playwright CLI助手模式行为。 - 无头基线(默认硬化):当
headless=true,MCP现在自动启用stealth+默认情况下,devtools会屏蔽(同时仍然尊重显式的运行时/CLI覆盖)。 - 严格预设模式:
--strict-preset防止预设拥有的密钥被无头默认硬化覆盖(显式CLI/运行时覆盖仍然有效)。 - 内置隐形预设:
--stealth口罩navigator.webdriver,存根chrome.runtime,注入真实的插件/mimeTypes、shims权限和掩码devtools/CDP探测(使用禁用devtools掩码--no-stealth-devtools,或启用它--stealth-devtools). - CDP连接模式:
--cdp-endpoint [ENDPOINT]启用CDP连接模式。如果ENDPOINT如果省略,则默认为http://127.0.0.1:1234/json/version如果不提供此标志,MCP将以正常启动模式运行。当直接剧作家会话被阻止或频繁出现验证码/WAF检查时,这通常更具弹性。 - 运行时间开关:使用
recreate_context(cdp_endpoint="http://127.0.0.1:1234/json/version", cdp_use_existing_context=True)热切换到CDP模式,或通过cdp_endpoint=""清除它并返回正常启动模式。 - 初始化脚本:
--init-script ./hacks.js通过以下方式注入自己的JScontext.add_init_script在执行任何页面脚本之前。 - 指纹旋钮(在创建上下文时应用):
--user-agent,--sec-ch-ua*,--accept-language,--languages,--locale,--timezone-id,--platform,--vendor,--hardware-concurrency,--device-memory,--device-scale-factor,以及已存在的视口标志。 - 权限塑造:
--grant-permissions geolocation,clipboard-read --permission-state notifications=granted预先授予上下文权限和覆盖navigator.permissions.query响应。 - 例子:
playwright-mcp stdio --stealth --user-agent "Mozilla/5.0 ..." --sec-ch-ua "\"Chromium\";v=\"122\", \"Google Chrome\";v=\"122\"" --languages en-US,en --platform MacIntel --vendor "Google Inc." --hardware-concurrency 8 --device-memory 8 --device-scale-factor 2.
防检测预设(选择加入)
- 启动时使用预设:
--antidetect-preset pixelscan或--antidetect-preset clearance-safe(选择加入,分层在默认反检测基线之上)。 - 通过工具在运行时应用:
apply_antidetect_preset(preset="pixelscan")/apply_antidetect_preset(preset="clearance-safe")或recreate_context(antidetect_preset="..."). - 对于严格的预设语义,请结合
--strict-preset启动或运行时recreate_context(strict_preset=true, antidetect_preset="..."). clearance-safe:headed Chrome频道,仅删除Playwright自动化标志(--disable-blink-features=AutomationControlled+--enable-automation剥离),固定视口1366x900,UAChrome/120在macOS上Accept-Language: en-US,en;q=0.9和地区en-US,没有隐形/CDP补丁,保留客户端提示和userAgentData本机,没有插件/运行时存根或devtools掩码。将此预留用于旋转栅门/WAF清关运行。pixelscan:令人头痛,stealth=True,Chrome频道,CDP传输补丁打开;使viewport/language/chrome.runtime/plugins保持未屏蔽状态;删除navigator.webdriver;将devtools哨兵设置为“关闭”;除非被覆盖,否则使用本机UA/CH/TZ。- 验证(实时,可选):
PIXELSCAN_RUN=1 PIXELSCAN_PRESET=pixelscan venv/bin/python -m pytest -s tests/test_pixelscan_botcheck.py(点击pixelscan.net/bot检查)。
标准反检测配置文件(团队手册)
在运行手册、事件和实验中一致使用这些名称。
max_stealth(最高反检测,速度较慢/较重):CDP附加到真实的Chrome配置文件。clearance(强大的WAF/挑战处理能力):主管+clearance-safe预设。fast_headless(最佳速度/吞吐量):无头,默认硬化。
启动命令:
# 1) max_stealth
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=1234 --user-data-dir=/tmp/pwmcp_cdp_profile
playwright-mcp stdio --cdp-endpoint
# 2) clearance
playwright-mcp stdio --antidetect-preset clearance-safe
# 3) fast_headless
playwright-mcp stdio --headless
运行时等效工具(MCP工具):
max_stealth:recreate_context(cdp_endpoint="http://127.0.0.1:1234/json/version", cdp_use_existing_context=True)clearance:recreate_context(antidetect_preset="clearance-safe")fast_headless:recreate_context(headless=True)(无头硬化是自动应用的)
笔记:
fast_headless现在自动启用强化默认值(stealth、devtools掩码和blink自动化剥离),除非明确覆盖。- 如果一个网站仍然面临挑战
fast_headless,升级到clearance,然后max_stealth.
与Claude Desktop集成
添加到您的 claude_desktop_config.json:
{
"mcpServers": {
"playwright": {
"command": "playwright-mcp",
"args": ["stdio"]
}
}
}
MCP检验员测试
# Install and run MCP inspector
uv run mcp dev src/playwright_mcp/server.py
响应预算和工件
大批量工具(evaluate, get_accessibility_snapshot, get_network_requests, get_network_responses, get_html等)遵守共享响应预算。当序列化的有效载荷超过 --max-response-chars:
- 内联结果被修剪以适应预算,并标记为
truncated: true. - 紧凑的
preview(默认400个字符)快照保留的内容。 - 完整的负载被写入工件目录(默认
tmp/playwright_mcp)并返回为overflow_path加上原始尺寸overflow_characters. - 使用
read_artifact工具(或在本地打开文件)以检索保存的有效载荷。二进制工件在读取时会回退到base64。 - 工件会自动修剪——默认情况下,任何超过两个小时的文件都会被删除,目录的文件上限为200个(
--artifact-max-age-seconds,--artifact-max-files).
二进制重型工具(screenshot, pdf, get_response_body 对于非文本有效载荷)现在默认为工件响应。它们返回元数据(大小、哈希、预览)加 artifact_path.通行证 inline=True 当你真正需要完整的base64内联时。
当您需要的不仅仅是内联预览时,请使用 read_artifact_chunk 在可管理的切片中流式传输二进制/文本工件(默认块大小可通过以下方式配置 --artifact-chunk-size).
调整每次跑步的上限 --max-response-chars, --preview-chars,以及 --artifact-dir 或者覆盖工具公开的每次调用限制。
api参考
工具
浏览器生命周期和反检测
restart_browser(headed: bool = True, channel: str | None = None, user_data_dir: str | None = None)-重新启动浏览器进程,并可选择切换headed/headless、channel或profile目录recreate_context(...)-使用指纹、反检测、权限、视口、初始化脚本和CDP选项重建浏览器上下文recreate_context(strict_preset: bool = True, antidetect_preset: str = "...")-保留预设拥有的密钥,防止无头默认硬化apply_antidetect_preset(preset: str = "pixelscan")-应用预设并重建上下文(严格行为遵循当前strict_preset设置)get_effective_config()-返回有效的浏览器/指纹设置,包括strict_preset
导航和页面控制
navigate(url: str)-导航到URLreload()-重新加载当前页面go_back()-回到历史go_forward()-在历史中前进get_current_url()-使用解析的组件和查询参数获取当前页面URLwait_for_url(url_pattern: str, timeout: int)-等待URL与模式匹配wait_for_load_state(state: str, timeout: int)-等待页面加载状态(domcontentloaded、load、networkidle)set_viewport_size(width: int, height: int)-设置视口尺寸
多页管理(选项卡/Windows)
list_pages()-列出所有打开的浏览器页面/选项卡,包括ID、URL和标题switch_page(page_id: str)-按ID切换到其他页面/选项卡close_page(page_id: str)-关闭特定页面/选项卡(不能关闭最后一个)wait_for_popup(timeout: int)-等待并捕获新的弹出窗口/选项卡switch_to_latest_page()-切换到最近打开的页面
元素交互
click(selector: str)-单击元素type_text(selector: str, text: str)-在元素中键入文本fill(selector: str, value: str)-填写输入字段clear_text(selector: str)-清除输入字段文本select_option(selector: str, value: str)-选择一个选项hover(selector: str)-将鼠标悬停在元素上scroll(selector: str, x: int, y: int)-滚动元件press_key(key: str)-按键盘键
表单处理
check_checkbox(selector: str)-选中复选框uncheck_checkbox(selector: str)-取消选中复选框upload_file(selector: str, file_path: str)-上传文件到输入
元素发现与验证
query_selector(selector: str, max_text_length: int | None = None)-查询单个元素(可选的每次调用文本上限覆盖)query_selector_all(selector: str, max_elements: int | None = None, max_text_length: int | None = None)-查询所有匹配的元素(可选的每次调用覆盖)query_selector_meta(selector: str, preview_length: int = 200, max_elements: int | None = None)-快速元数据预览(标签、角色、短文本、关键属性)- 元素查询工具遵循全局上限,接受每次调用的覆盖,并返回
truncated/returned_count在剪切结果时使用元数据。 is_visible(selector: str)-检查元素是否可见is_enabled(selector: str)-检查元件是否启用wait_for_element(selector: str, timeout: int)-等待元素出现get_element_bounding_box(selector: str)-获取元素位置和大小get_element_attributes(selector: str)-获取所有元素属性get_computed_style(selector: str, property: str)-获取CSS计算样式
脚本评估和诊断
evaluate(script: str)-在页面上下文中执行JavaScript(结果遵守共享响应预算,并根据需要发出溢出元数据)
网络监控和溢出检索
get_network_requests(url_pattern: str | None = None)-检查捕获的请求;大型结果集会溢出到带有预览的工件中get_network_responses(url_pattern: str | None = None)-使用相同的预算行为检查捕获的响应read_artifact(path: str)-加载先前响应中引用的溢出工件的第一个块(返回文本或base64内容)read_artifact_chunk(path: str, offset: int = 0, limit: int | None = None)-以有界块的形式流式传输额外的工件数据get_response_body(url_pattern: str)-获取最新匹配的响应体;文本是内联预算的,二进制有效载荷会自动保存到工件中
内容和快照
get_html()-获取页面HTMLget_accessibility_snapshot(interesting_only: bool = True, root_selector: str | None = None, max_nodes: int | None = None)-获取带有可选过滤器和每个调用节点上限的可访问性树- 可访问性快照被修剪到配置的节点预算,接受每次调用的覆盖,并包括
truncated,max_nodes,以及node_count元数据。 - 当剧作家缺乏
page.accessibility,工具将回退到locator.aria_snapshot()并返回format: "aria_snapshot"(估计节点计数)。 screenshot(selector: str | None = None, full_page: bool = False, inline: bool = False)-捕获页面或元素;默认情况下,将PNG存储为具有元数据预览的工件pdf(inline: bool = False)-除非明确请求内联模式,否则生成PDF并返回工件元数据
JavaScript和调试
evaluate(script: str)-在页面上下文中执行JavaScriptwait_for_network_idle(timeout: int)-等待网络活动稳定get_page_errors()-从页面获取JavaScript错误get_console_logs()-从页面获取控制台输出
网络监控与拦截
get_network_requests(url_pattern: str)-通过过滤检索捕获的网络请求get_network_responses(url_pattern: str)-通过过滤检索捕获的网络响应clear_network_logs()-清除所有捕获的网络请求/响应日志intercept_route(url_pattern: str, action: str, ...)-拦截和处理网络请求unroute_all()-删除所有路由拦截器wait_for_response(url_pattern: str, timeout: int)-等待特定的网络响应get_response_body(url_pattern: str)-从网络呼叫中提取响应正文内容
Cookie管理
get_cookies(urls: List[str])-使用可选的URL过滤检索浏览器Cookieadd_cookies(cookies: List[Dict])-在浏览器上下文中添加Cookieclear_cookies(name: str, domain: str)-通过可选过滤清除Cookie
存储管理
load_storage_state(path: str, origin_urls: List[str] | None = None)-加载剧作家storage_stateJSON文件转换到当前浏览器上下文中;只返回计数/元数据,从不返回cookie或localStorage值save_storage_state(path: str)-保存当前浏览器上下文storage_state到一个文件;只返回计数/元数据,从不返回cookie或localStorage值get_local_storage(origin: str)-访问本地存储数据set_local_storage(key: str, value: str)-设置本地存储项get_session_storage()-访问会话存储数据set_session_storage(key: str, value: str)-设置会话存储项clear_storage(storage_type: str)-清除本地存储和/或会话存储
请求标头和身份
set_extra_headers(headers: Dict)-向所有请求添加自定义HTTP标头set_user_agent(user_agent: str)-更改浏览器用户代理字符串
例子
处理多个页面/标签
服务器会自动跟踪所有浏览器页面/选项卡:
# Example: Clicking a link that opens in a new tab
1. navigate("https://example.com")
2. click("a[target='_blank']") # Opens new tab
3. list_pages() # Shows all open tabs with IDs
4. switch_to_latest_page() # Switch to the new tab
5. get_current_url() # Get URL of new tab
6. switch_page(original_page_id) # Switch back
# Example: Handling JavaScript popups
1. evaluate("window.open('https://example.com', '_blank')")
2. wait_for_popup(timeout=5000) # Wait for and capture popup
3. list_pages() # See all pages including popup
4. close_page(popup_id) # Close the popup
所有现有工具都会自动在当前活动页面上工作。切换页面时,后续操作将应用于新的活动页面。
配置
服务器接受以下配置选项:
--headed/--headless-强制头模式或无头模式(默认为无头)。除非明确覆盖,否则无头模式自动启用强化的反检测默认值。--strict-preset-当与--antidetect-preset,保留预设键以防止无头默认硬化(显式覆盖仍然有效)--browser-浏览器类型(chromium、firefox、webkit)--channel-适用于真实浏览器的浏览器频道(chrome、chrome beta、msedge等)--user-data-dir-持久上下文的浏览器配置文件目录路径--cdp-endpoint [ENDPOINT]-启用CDP连接模式。如果ENDPOINT省略,默认为http://127.0.0.1:1234/json/version;如果没有提供标记,MCP将以正常启动模式运行(建议在被阻止或验证码过多时)--cdp-use-existing-context/--no-cdp-use-existing-context-重用第一个CDP上下文或强制使用新的CDP上下文--cdp-close-browser/--no-cdp-close-browser-控制关闭时是否关闭连接的浏览器--port-HTTP传输端口--timeout-操作的默认超时时间(ms)--max-elements-查询工具返回的DOM节点的最大数量(默认值:20)--max-element-text-length-元素文本和属性值返回的最大字符数(默认值:2000)--max-accessibility-nodes-返回的最大可访问性树节点数get_accessibility_snapshot(默认值:500)--max-response-chars-在结果溢出到工件文件之前内联返回的最大序列化字符数(默认值:4000)--preview-chars-截断时内联预览中包含的最大字符数(默认值:400)--artifact-dir-写入溢出工件的目录(默认:./tmp/playwright_mcp)--artifact-max-age-seconds-清除工件前的最长时间(默认值:7200秒)--artifact-max-files-目录中保存的工件文件的最大数量(默认值:200)--artifact-chunk-size-每个返回的默认字节数read_artifact_chunk呼叫(默认值:4096)
所有上限均接受 0 或负值以完全禁用截断。当发生截断时,工具响应包括 truncated 标记和元数据,以便客户端可以选择重新发出更窄的请求。
真正的铬与捆绑铬
默认情况下,Playwright使用捆绑的Chromium。对于需要真正Chrome功能的网页抓取:
使用 --channel chrome 要使用已安装的Google Chrome浏览器:
- 访问所有Chrome功能和编解码器
- 与某些网站的兼容性更好
- Chrome特定行为
使用 --user-data-dir 要访问您的真实个人资料:
- 您的所有Cookie和登录会话
- 浏览器扩展(AdBlock等)
- 浏览历史记录和自动填充数据
- 书签和保存的密码
macOS示例:
playwright-mcp stdio --channel chrome --user-data-dir "/Users/$(whoami)/Library/Application Support/Google/Chrome"
Linux示例:
playwright-mcp stdio --channel chrome --user-data-dir "/home/$(whoami)/.config/google-chrome"
发展
# Clone the repository
git clone <repo-url>
cd playwright-mcp
# Install dependencies
uv sync --dev
# Run tests
uv run pytest
# Format code
uv run black src/
uv run ruff check src/
# Type check
uv run mypy src/
许可证
麻省理工学院