playwright-automation
Playwrightを使って、ウェブサイトの操作を自動化し、データ収集やフォーム入力、UIテストなどを効率的に行い、定型業務を自動化するSkill。
📜 元の英語説明(参考)
Playwright 浏览器自动化。用于自动化爬虫、数据采集、表单填写、UI 测试等需要浏览器自动化的场景。无需人工干预,适合 cron 定时任务。
🇯🇵 日本人クリエイター向け解説
Playwrightを使って、ウェブサイトの操作を自動化し、データ収集やフォーム入力、UIテストなどを効率的に行い、定型業務を自動化するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o playwright-automation.zip https://jpskill.com/download/8479.zip && unzip -o playwright-automation.zip && rm playwright-automation.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/8479.zip -OutFile "$d\playwright-automation.zip"; Expand-Archive "$d\playwright-automation.zip" -DestinationPath $d -Force; ri "$d\playwright-automation.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
playwright-automation.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
playwright-automationフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Playwright ブラウザ自動化
概要
Playwright は強力なブラウザ自動化ツールであり、実際のユーザー操作をシミュレートでき、以下をサポートします。
- ヘッドレスブラウザモード(バックグラウンド実行)
- データ収集とクローリング
- フォームの自動入力
- UI 自動化テスト
- スクリーンショットと PDF 生成
Playwright が必要な理由
browser tool との違い
| 特性 | browser tool | Playwright |
|---|---|---|
| ユーザーの関与が必要 | ✅ 手動でブラウザを開く必要がある | ❌ 完全自動 |
| 定期タスクに適しているか | ❌ | ✅ |
| バックグラウンド実行 | ❌ | ✅ |
| デバッグのしやすさ | ✅ 可視化操作 | ⚠️ ログが必要 |
| インストール不要 | ✅ 統合済み | ❌ インストールが必要 |
使用シナリオ
Playwright の使用:
- ✅ 定期的な監視(cron ジョブ)
- ✅ 大規模なデータ収集
- ✅ 無人での実行
- ✅ 本番環境へのデプロイ
browser tool の使用:
- ✅ インタラクティブなデバッグ
- ✅ 人間の判断が必要な操作
- ✅ 一度限りのタスク
- ✅ 複雑な検証コードの回避
快速开始
1. Playwright のインストール
# Python パッケージのインストール
pip install playwright
# ブラウザ(Chromium)のインストール
playwright install chromium
# インストール確認
python3 -c "from playwright.sync_api import sync_playwright; print('✅ インストール成功')"
2. 基本的な使い方
同期 API(簡単なタスク)
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True) # headless=False でブラウザを表示
page = browser.new_page()
page.goto('https://example.com')
print(page.title())
browser.close()
非同期 API(推奨、パフォーマンスが向上)
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto('https://example.com')
title = await page.title()
print(title)
await browser.close()
asyncio.run(main())
常用功能
1. ページナビゲーション
# ロード完了を待機
await page.goto('https://example.com', wait_until='domcontentloaded')
# 待機オプション:
# - 'load' - ページが完全にロードされるまで
# - 'domcontentloaded' - DOM のロード完了まで(より高速)
# - 'networkidle' - ネットワークがアイドル状態になるまで(最も遅いが最も安定)
2. 要素の特定
# CSS セレクター
await page.click('button.submit')
await page.fill('input[name="username"]', 'myuser')
# XPath
await page.click('xpath=//button[@type="submit"]')
# テキストセレクター
await page.click('text=登录')
# 組み合わせセレクター
await page.click('div.login-form >> text=登录')
3. データの抽出
# テキストの取得
text = await page.text_content('h1.title')
# 属性の取得
href = await page.get_attribute('a.link', 'href')
# 複数の要素の取得
items = await page.query_selector_all('div.item')
for item in items:
text = await item.text_content()
print(text)
# JavaScript の実行
result = await page.evaluate('() => document.title')
# HTML 全体の取得
html = await page.content()
4. フォーム操作
# フォームの入力
await page.fill('input[name="username"]', 'myuser')
await page.fill('input[name="password"]', 'mypass')
await page.click('button[type="submit"]')
# ドロップダウン選択
await page.select_option('select#country', 'China')
# チェックボックス
await page.check('input#agree')
# ファイルのアップロード
await page.set_input_files('input[type="file"]', 'path/to/file.pdf')
5. 待機戦略
# 要素の出現を待機
await page.wait_for_selector('div.result', timeout=5000)
# ナビゲーションの待機
async with page.expect_navigation():
await page.click('a.link')
# 特定の条件の待機
await page.wait_for_function('() => document.title.includes("加载完成")')
# 固定遅延
import asyncio
await asyncio.sleep(2) # 2 秒待機
6. スクロールとインタラクション
# ページの一番下までスクロール
await page.evaluate('window.scrollTo(0, document.body.scrollHeight)')
# 要素までスクロール
await page.locator('div.footer').scroll_into_view_if_needed()
# マウスオーバー
await page.hover('div.menu')
# ドラッグアンドドロップ
await page.drag_and_drop('div.draggable', 'div.dropzone')
7. スクリーンショットと PDF
# スクリーンショット
await page.screenshot(path='screenshot.png')
# ページ全体のスクリーンショット
await page.screenshot(path='full.png', full_page=True)
# 要素のスクリーンショット
await page.locator('div.content').screenshot(path='element.png')
# PDF の生成
await page.pdf(path='page.pdf', format='A4')
8. ポップアップの処理
# alert の受け入れ
async with page.expect_event('dialog') as dialog_info:
await page.click('button')
dialog = await dialog_info.value
await dialog.accept()
# prompt の入力
async with page.expect_event('dialog') as dialog_info:
await page.click('button')
dialog = await dialog_info.value
await dialog.accept('my input')
アンチクローリング戦略
1. User-Agent ローテーション
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
]
browser = await p.chromium.launch(
user_agent=random.choice(user_agents)
)
2. ランダムな遅延
import random
import asyncio
# 操作間にランダムな遅延を追加
await asyncio.sleep(random.uniform(2, 5))
3. Cookie の保存とロード
# 最初のログイン後に Cookie を保存
context = await browser.new_context()
await page.goto('https://example.com/login')
# ... ログイン操作 ...
await context.storage_state(path='cookies.json')
# 保存された Cookie を後で使用
context = await browser.new_context(storage_state='cookies.json')
4. プロキシ設定
browser = await p.chromium.launch(
proxy={
'server': 'http://proxy.example.com:8080',
'username': 'user',
'password': 'pass'
}
)
5. ブラウザコンテキストの分離
# 独立したコンテキストを作成(シークレットモードに相当)
context = await browser.new_context(
viewport={'width': 1920, 'height': 1080},
user_agent='Custom UA',
locale='zh-CN'
)
page = await context.new_page()
デバッグのヒント
1. ブラウザの表示
# ヘッドレスモードをオフにして、操作プロセスを表示
browser = await p.chromium.launch(headless=False, slow_mo=1000)
# slow_mo=1000 は各操作間に 1 秒の遅延を追加します
2. スクリーンショットデバッグ
# 重要なステップでスクリーンショットを撮る
await page.goto('https://example.com')
await page.screenshot(path='step1.png')
await page.click('button')
await page.screenshot(path='step2.png')
3. ログの確認
# コンソールメッセージをリッスン
page.on('console', lambda msg: print(f'Console: {msg.text}'))
# ネットワークリクエストをリッスン
page.on('request', lambda request: print(f'Request: {request.url}'))
page.on('response', lambda response: print(f'Response: {response.status}'))
4. Playwright Inspector
# Inspector モードを起動
PWDEBUG=1 python3 your_script.py
よくある質問
Q: 検証コードを処理するには?
A: いくつかの解決策
- コード認識プラットフォーム(超级鹰、若快打码)を使用
- 手動で処理:ユーザーの入力を待機するために一時停止
- ダウングレード:browser tool を使用してユーザーに手動で操作させる
# 解決策 2: 手動で処理
input("検証コードが表示されたら、ブラウザで完了し、Enter キーを押して続行してください...")
await asyncio.sleep(2) # 検証が完了するまで待機
Q: 要素が見つからない場合はどうすればよいですか?
A: 以下の点を確認してください
- iframe 内にあるか(切り替えが必要)
- 動的にロードされるか(待機が必要)
- セレクターが正しいか
(原文はここで切り捨てられています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Playwright 浏览器自动化
概述
Playwright 是一个强大的浏览器自动化工具,可以模拟真实用户操作,支持:
- 无头浏览器模式(后台运行)
- 数据采集和爬虫
- 表单自动填写
- UI 自动化测试
- 截图和 PDF 生成
为什么需要 Playwright
与 browser tool 的区别
| 特性 | browser tool | Playwright |
|---|---|---|
| 需要用户参与 | ✅ 需要手动打开浏览器 | ❌ 完全自动 |
| 适合定时任务 | ❌ | ✅ |
| 后台运行 | ❌ | ✅ |
| 调试友好 | ✅ 可视化操作 | ⚠️ 需要日志 |
| 无需安装 | ✅ 已集成 | ❌ 需要安装 |
使用场景
使用 Playwright:
- ✅ 定时监控(cron 任务)
- ✅ 大规模数据采集
- ✅ 无人值守运行
- ✅ 生产环境部署
使用 browser tool:
- ✅ 交互式调试
- ✅ 需要人工决策的操作
- ✅ 一次性任务
- ✅ 绕过复杂验证码
快速开始
1. 安装 Playwright
# 安装 Python 包
pip install playwright
# 安装浏览器(Chromium)
playwright install chromium
# 验证安装
python3 -c "from playwright.sync_api import sync_playwright; print('✅ 安装成功')"
2. 基本使用
同步 API(简单任务)
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True) # headless=False 显示浏览器
page = browser.new_page()
page.goto('https://example.com')
print(page.title())
browser.close()
异步 API(推荐,性能更好)
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto('https://example.com')
title = await page.title()
print(title)
await browser.close()
asyncio.run(main())
常用功能
1. 页面导航
# 等待加载完成
await page.goto('https://example.com', wait_until='domcontentloaded')
# 等待选项:
# - 'load' - 页面完全加载
# - 'domcontentloaded' - DOM 加载完成(更快)
# - 'networkidle' - 网络空闲(最慢但最稳)
2. 元素定位
# CSS 选择器
await page.click('button.submit')
await page.fill('input[name="username"]', 'myuser')
# XPath
await page.click('xpath=//button[@type="submit"]')
# 文本选择器
await page.click('text=登录')
# 组合选择器
await page.click('div.login-form >> text=登录')
3. 提取数据
# 获取文本
text = await page.text_content('h1.title')
# 获取属性
href = await page.get_attribute('a.link', 'href')
# 获取多个元素
items = await page.query_selector_all('div.item')
for item in items:
text = await item.text_content()
print(text)
# 执行 JavaScript
result = await page.evaluate('() => document.title')
# 获取整个 HTML
html = await page.content()
4. 表单操作
# 填写表单
await page.fill('input[name="username"]', 'myuser')
await page.fill('input[name="password"]', 'mypass')
await page.click('button[type="submit"]')
# 下拉选择
await page.select_option('select#country', 'China')
# 复选框
await page.check('input#agree')
# 上传文件
await page.set_input_files('input[type="file"]', 'path/to/file.pdf')
5. 等待策略
# 等待元素出现
await page.wait_for_selector('div.result', timeout=5000)
# 等待导航
async with page.expect_navigation():
await page.click('a.link')
# 等待特定条件
await page.wait_for_function('() => document.title.includes("加载完成")')
# 固定延迟
import asyncio
await asyncio.sleep(2) # 等待 2 秒
6. 滚动和交互
# 滚动到页面底部
await page.evaluate('window.scrollTo(0, document.body.scrollHeight)')
# 滚动到元素
await page.locator('div.footer').scroll_into_view_if_needed()
# 鼠标悬停
await page.hover('div.menu')
# 拖拽
await page.drag_and_drop('div.draggable', 'div.dropzone')
7. 截图和 PDF
# 截图
await page.screenshot(path='screenshot.png')
# 全页截图
await page.screenshot(path='full.png', full_page=True)
# 元素截图
await page.locator('div.content').screenshot(path='element.png')
# 生成 PDF
await page.pdf(path='page.pdf', format='A4')
8. 处理弹窗
# 接受 alert
async with page.expect_event('dialog') as dialog_info:
await page.click('button')
dialog = await dialog_info.value
await dialog.accept()
# 输入 prompt
async with page.expect_event('dialog') as dialog_info:
await page.click('button')
dialog = await dialog_info.value
await dialog.accept('my input')
反爬策略
1. User-Agent 轮换
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
]
browser = await p.chromium.launch(
user_agent=random.choice(user_agents)
)
2. 随机延迟
import random
import asyncio
# 在操作之间添加随机延迟
await asyncio.sleep(random.uniform(2, 5))
3. Cookie 保存和加载
# 第一次登录后保存 Cookie
context = await browser.new_context()
await page.goto('https://example.com/login')
# ... 登录操作 ...
await context.storage_state(path='cookies.json')
# 后续使用保存的 Cookie
context = await browser.new_context(storage_state='cookies.json')
4. 代理设置
browser = await p.chromium.launch(
proxy={
'server': 'http://proxy.example.com:8080',
'username': 'user',
'password': 'pass'
}
)
5. 浏览器上下文隔离
# 创建独立的上下文(相当于无痕模式)
context = await browser.new_context(
viewport={'width': 1920, 'height': 1080},
user_agent='Custom UA',
locale='zh-CN'
)
page = await context.new_page()
调试技巧
1. 显示浏览器
# 开启有头模式,可以看到操作过程
browser = await p.chromium.launch(headless=False, slow_mo=1000)
# slow_mo=1000 会在每个操作间延迟 1 秒
2. 截图调试
# 在关键步骤截图
await page.goto('https://example.com')
await page.screenshot(path='step1.png')
await page.click('button')
await page.screenshot(path='step2.png')
3. 查看日志
# 监听控制台消息
page.on('console', lambda msg: print(f'Console: {msg.text}'))
# 监听网络请求
page.on('request', lambda request: print(f'Request: {request.url}'))
page.on('response', lambda response: print(f'Response: {response.status}'))
4. Playwright Inspector
# 启动 Inspector 模式
PWDEBUG=1 python3 your_script.py
常见问题
Q: 如何处理验证码?
A: 几种方案
- 使用打码平台(超级鹰、若快打码)
- 手动处理:暂停等待用户输入
- 降级:用 browser tool 让用户手动操作
# 方案 2: 手动处理
input("遇到验证码,请在浏览器中完成,然后按回车继续...")
await asyncio.sleep(2) # 等待验证通过
Q: 元素找不到怎么办?
A: 检查以下几点
- 是否在 iframe 中(需要切换)
- 是否动态加载(需要等待)
- 选择器是否正确
# 切换到 iframe
frame = page.frame('iframe-id')
await frame.click('button')
# 等待动态加载
await page.wait_for_selector('div.dynamic-content')
Q: 如何提高性能?
A:
- 使用异步 API
- 并发多个页面
- 减少不必要的等待
# 并发多个页面
async def fetch(url):
page = await browser.new_page()
await page.goto(url)
# ...
tasks = [fetch(url) for url in urls]
await asyncio.gather(*tasks)
与 OpenClaw 集成
在 healthcare-monitor 中的使用
# scraper_free.py
from playwright.async_api import async_playwright
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
context = await browser.new_context(
user_agent="Mozilla/5.0 ..."
)
page = await context.new_page()
await page.goto(url)
# ... 采集数据 ...
await browser.close()
与 browser tool 配合
- Playwright → 日常自动监控
- browser tool → 调试和异常处理
资源
- 官方文档: https://playwright.dev/python/
- API 参考: https://playwright.dev/python/docs/api/class-playwright
- 示例代码:
~/clawd/skills/playwright-automation/examples/
快速命令
# 安装
pip install playwright && playwright install chromium
# 运行脚本
python3 script.py
# 调试模式
PWDEBUG=1 python3 script.py
# 查看版本
playwright --version
记住: Playwright 让你的自动化任务完全无人值守!🚀