なぜPlaywrightがブラウザ自動化を支配するのか:深い掘り下げ
Wenhao Wang
Dev Intern · Leapcell

PlayWrightは、Microsoftによって開発されたWeb UI自動化テストフレームワークです。 モバイルブラウザもサポートする、クロスプラットフォーム、クロス言語、クロスブラウザの自動化テストフレームワークを提供することを目指しています。
公式ホームページで説明されているように、
- 自動待機、ページ要素に対するインテリジェントなアサーション、および実行トレースにより、Webページの不安定さを非常に効果的に処理できます。
- テストを実行するプロセスとは異なるプロセスでブラウザを制御し、インプロセステストランナーの制限を排除し、Shadow DOMの透過性をサポートします。
- PlayWrightは、各テストに対してブラウザコンテキストを作成します。ブラウザコンテキストは、真新しいブラウザプロファイルと同等であり、ゼロコストの完全なテスト分離を可能にします。新しいブラウザコンテキストの作成には、わずか数ミリ秒しかかかりません。
- コード生成、ステップバイステップのデバッグ、トレースビューアなどの機能を提供します。
PlayWright vs. Selenium vs. Cypress
今日利用できる最高のWeb UI自動化テストフレームワークは何でしょうか?傑出したオプションには、10年前のSelenium、最近人気のCypress、そしてここで紹介するPlayWrightがあります。それらはどのように異なるのでしょうか?以下に、参考のために要約された比較を示します。
Feature | PlayWright | Selenium | Cypress |
---|---|---|---|
Supported Languages | JavaScript, Java, C#, Python | JavaScript, Java, C#, Python, Ruby | JavaScript/TypeScript |
Supported Browsers | Chrome, Edge, Firefox, Safari | Chrome, Edge, Firefox, Safari, IE | Chrome, Edge, Firefox, Safari |
Testing Framework | Frameworks for supported languages | Frameworks for supported languages | Frameworks for supported languages |
Usability | Easy to use and configure | Complex setup with a learning curve | Easy to use and configure |
Code Complexity | Simple | Moderate | Simple |
DOM Manipulation | Simple | Moderate | Simple |
Community Maturity | Improving gradually | Highly mature | Fairly mature |
Headless Mode Support | Yes | Yes | Yes |
Concurrency Support | Supported | Supported | Depends on CI/CD tools |
iframe Support | Supported | Supported | Supported via plugins |
Driver | Not required | Requires a browser-specific driver | Not required |
Multi-Tab Operations | Supported | Not supported | Supported |
Drag and Drop | Supported | Supported | Supported |
Built-in Reporting | Yes | No | Yes |
Cross-Origin Support | Supported | Supported | Supported |
Built-in Debugging | Yes | No | Yes |
Automatic Wait | Yes | No | Yes |
Built-in Screenshot/Video | Yes | No video recording | Yes |
Key Comparisons:
- Supported Languages: PlayWrightとSeleniumはJava、C#、Pythonをサポートしており、JavaScript/TypeScriptに馴染みのないテストエンジニアの間でより人気があります。
- Technical Approach: PlayWrightとSeleniumはどちらも、GoogleのRemote Debugging Protocolを使用してChromiumベースのブラウザを制御します。そのようなプロトコルがないFirefoxのようなブラウザの場合、JavaScriptインジェクションを使用します。SeleniumはこれをDriverにカプセル化しますが、PlayWrightは直接呼び出します。一方、CypressはJavaScriptを使用してブラウザを制御します。
- Browser Support: SeleniumはInternet Explorerをサポートしていますが、IEは段階的に廃止されているため、無関係です。
- Ease of Use: 3つのフレームワークすべてに学習曲線があります。ただし、PlayWrightとCypressは、Seleniumと比較して、単純なシナリオではよりユーザーフレンドリーです。
Getting Started
PlayWrightは複数の言語をサポートしていますが、Node.jsに大きく依存しています。PythonまたはJavaバージョンのどちらを使用する場合でも、PlayWrightは初期化時にNode.js環境を必要とし、Node.jsドライバーをダウンロードします。したがって、このガイドではJavaScript/TypeScriptに焦点を当てます。
Installation and Demo
-
Ensure Node.js is installed.
-
npm
またはyarn
を使用してPlayWrightプロジェクトを初期化します。# Using npm npm init playwright@latest # Using yarn yarn create playwright
-
プロンプトに従います。
- TypeScriptまたはJavaScriptを選択します(デフォルト:TypeScript)。
- テストディレクトリ名を指定します。
- PlayWrightでサポートされているブラウザをインストールするかどうかを決定します(デフォルト:True)。
ブラウザをダウンロードすることを選択した場合、PlayWrightはChromium、Firefox、WebKitをダウンロードします。これには時間がかかる場合があります。このプロセスは、PlayWrightバージョンが更新されない限り、最初のセットアップ時にのみ発生します。
Project Structure
初期化後、プロジェクトテンプレートが表示されます。
playwright.config.ts # PlayWright configuration file
package.json # Node.js configuration file
package-lock.json # Node.js dependency lock file
tests/ # Your test directory
example.spec.ts # Template test case
tests-examples/ # Example tests directory
demo-todo-app.spec.ts # Example test case
サンプルテストケースを実行します。
npx playwright test
テストは(ヘッドレスモードで)静かに実行され、結果は次のように表示されます。
Running 6 tests using 6 workers
6 passed (10s)
To open the last HTML report run:
npx playwright show-report
Example Source Code
以下はexample.spec.ts
テストケースです。
import { test, expect } from '@playwright/test'; test('has title', async ({ page }) => { await page.goto('https://playwright.dev/'); await expect(page).toHaveTitle(/Playwright/); }); test('get started link', async ({ page }) => { await page.goto('https://playwright.dev/'); await page.getByRole('link', { name: 'Get started' }).click(); await expect(page).toHaveURL(/.*intro/); });
- First Test: ページタイトルに「Playwright」が含まれていることを確認します。
- Second Test: 「Get started」リンクをクリックし、URLを確認します。
各test
メソッドには、次が含まれます。
- テスト名(例:
'has title'
)。 - テストロジックを実行する関数。
主要なメソッドは次のとおりです。
page.goto
: URLに移動します。expect(page).toHaveTitle
: ページタイトルをアサートします。page.getByRole
: ロールで要素を検索します。await
: 非同期操作の完了を待ちます。
Running Tests from the Command Line
一般的なコマンドを次に示します。
- すべてのテストを実行します。
npx playwright test
- 特定のテストファイルを実行します。
npx playwright test landing-page.spec.ts
- テストケースをデバッグします。
npx playwright test --debug
Code Recording
codegen
機能を使用して、インタラクションを記録します。
npx playwright codegen https://leapcell.io/
記録されたコードは、ファイルにコピーできます。注:レコーダーは、ホバーなどの複雑なアクションを処理できない場合があります。
In-Depth Playwright Guide
Actions and Behaviors
このセクションでは、ページ要素を操作するための一般的なPlaywrightアクションをいくつか紹介します。以前に紹介したlocator
オブジェクトは、作成時にページ上の要素を実際には特定しないことに注意してください。要素がページに存在しない場合でも、要素ロケーターメソッドを使用してlocator
オブジェクトを取得しても、例外はスローされません。実際の要素ルックアップは、インタラクション中にのみ発生します。これは、SeleniumのfindElement
メソッドとは異なり、ページ上の要素を直接検索し、要素が見つからない場合は例外をスローします。
Text Input
テキスト入力にはfill
メソッドを使用します。これは、主に<input>
、<textarea>
、または[contenteditable]
属性を持つ要素を対象としています。
// Text input await page.getByRole('textbox').fill('Peter');
Checkbox and Radio
input[type=checkbox]
、input[type=radio]
、または[role=checkbox]
属性を持つ要素を操作するには、locator.setChecked()
またはlocator.check()
を使用します。
await page.getByLabel('I agree to the terms above').check(); expect(await page.getByLabel('Subscribe to newsletter').isChecked()).toBeTruthy(); // Uncheck await page.getByLabel('XL').setChecked(false);
Select Control
<select>
要素を操作するには、locator.selectOption()
を使用します。
// Select by value await page.getByLabel('Choose a color').selectOption('blue'); // Select by label await page.getByLabel('Choose a color').selectOption({ label: 'Blue' }); // Multi-select await page.getByLabel('Choose multiple colors').selectOption(['red', 'green', 'blue']);
Mouse Clicks
基本的な操作:
// Left click await page.getByRole('button').click(); // Double click await page.getByText('Item').dblclick(); // Right click await page.getByText('Item').click({ button: 'right' }); // Shift+click await page.getByText('Item').click({ modifiers: ['Shift'] }); // Hover await page.getByText('Item').hover(); // Click at specific position await page.getByText('Item').click({ position: { x: 0, y: 0 } });
他の要素で覆われている要素の場合は、強制クリックを使用します。
await page.getByRole('button').click({ force: true });
または、プログラムでクリックイベントをトリガーします。
await page.getByRole('button').dispatchEvent('click');
Typing Characters
locator.type()
メソッドは、文字を入力するのをシミュレートし、keydown
、keyup
、およびkeypress
イベントをトリガーします。
await page.locator('#area').type('Hello World!');
Special Keys
特殊キーにはlocator.press()
を使用します。
// Enter key await page.getByText('Submit').press('Enter'); // Ctrl+Right Arrow await page.getByRole('textbox').press('Control+ArrowRight'); // Dollar key await page.getByRole('textbox').press('$');
サポートされているキーには、Backquote
、Minus
、Equal
、Backslash
、Backspace
、Tab
、Delete
、Escape
、ArrowDown
、End
、Enter
、Home
、Insert
、PageDown
、PageUp
、ArrowRight
、ArrowUp
、F1-F12
、Digit0-Digit9
、およびKeyA-KeyZ
が含まれます。
File Upload
アップロードするファイルを指定するには、locator.setInputFiles()
を使用します。複数のファイルがサポートされています。
// Upload a file await page.getByLabel('Upload file').setInputFiles('myfile.pdf'); // Upload multiple files await page.getByLabel('Upload files').setInputFiles(['file1.txt', 'file2.txt']); // Remove files await page.getByLabel('Upload file').setInputFiles([]); // Upload from buffer await page.getByLabel('Upload file').setInputFiles({ name: 'file.txt', mimeType: 'text/plain', buffer: Buffer.from('this is test') });
Focus Element
要素にフォーカスするには、locator.focus()
を使用します。
await page.getByLabel('Password').focus();
Drag and Drop
ドラッグアンドドロッププロセスには、4つのステップが含まれます。
- ドラッグ可能な要素にマウスを合わせます。
- 左マウスボタンを押します。
- マウスをターゲット位置に移動します。
- 左マウスボタンを離します。
locator.dragTo()
メソッドを使用できます。
await page.locator('#item-to-be-dragged').dragTo(page.locator('#item-to-drop-at'));
または、プロセスを手動で実装します。
await page.locator('#item-to-be-dragged').hover(); await page.mouse.down(); await page.locator('#item-to-drop-at').hover(); await page.mouse.up();
Dialog Handling
デフォルトでは、Playwrightはalert
、confirm
、prompt
などのダイアログを自動的にキャンセルします。ダイアログを受け入れるようにダイアログハンドラーを事前に登録できます。
page.on('dialog', dialog => dialog.accept()); await page.getByRole('button').click();
Handling New Pages
新しいページがポップアップした場合、popup
イベントを使用して処理できます。
const newPagePromise = page.waitForEvent('popup'); await page.getByText('Click me').click(); const newPage = await newPagePromise; await newPage.waitForLoadState(); console.log(await newPage.title());
The Best Platform for Playwright: Leapcell
Leapcellは、分散アプリケーション向けに設計された最新のクラウドコンピューティングプラットフォームです。アイドルコストなしの従量課金モデルを採用し、使用したリソースに対してのみ料金を支払うことを保証します。
Unique Benefits of Leapcell for Playwright Applications
-
Cost Efficiency
- Pay-as-you-go: Avoid resource waste during low traffic and scale up automatically during peak times.
- Real-world example: For example, on getdeploying.com’s calculations, renting a 1 vCPU and 2 GB RAM virtual machine in traditional cloud services costs around $25 per month. On Leapcell, $25 can support a service handling 6.94 million requests with an average response time of 60 ms, giving you better value for money.
-
Developer Experience
- Ease of use: Intuitive interface with minimal setup requirements.
- Automation: Simplifies development, testing, and deployment.
- Seamless integration: Supports Go, Python, Node.js, Rust, and more.
-
Scalability and Performance
- Auto-scaling: Dynamically adjusts resources to maintain optimal performance.
- Asynchronous optimization: Handles high-concurrency tasks with ease.
- Global reach: Low-latency access supported by distributed data centers.
For more deployment examples, refer to the documentation.