🎭

[Playwright] 高度なロケーターのfilter()種類と使い方

に公開

はじめに

この記事では、Playwright の filter() についてをまとめております。

結論

1. 特定のテキストを持つ: { hasText: テキスト }

// getByRole('button') でページ上のすべてのボタンを取得
// filter({ hasText: 'Login' }) で「Login」というテキストを持つボタンをフィルタリング
// そのボタンをクリック
await page.getByRole("button").filter({ hasText: "/Login/" }).click();

2. 特定のテキストを持たない: { hasNotText: テキスト }

// getByRole('button') でページ上のすべてのボタンを取得
// filter({ hasText: 'Login' }) で「Login」というテキストを持たないボタンをフィルタリング
// そのボタンをクリック
await page.getByRole("button").filter({ hasNotText: "/Login/" }).click();

3. 特定の属性を持つ: { has: ロケーター }

// getByRole('textbox') でテキスト入力フィールドを取得
// filter({ has: page.locator('input[name="email"]') }) でname="email"属性を持つ入力フィールドをフィルタリング
await page.getByRole("textbox").filter({ has: page.locator('input[name="email"]') });

4. 特定の属性を持たない: { hasNot: ロケーター }

// getByRole('textbox') でテキスト入力フィールドを取得
// filter({ has: page.locator('input[name="email"]') }) でname="email"属性を持たない入力フィールドをフィルタリング
await page.getByRole("textbox").filter({ hasNot: page.locator('input[name="email"]') });

5. 複数の条件で絞り込む

// getByRole('button') でボタンを取得
// filter({ hasText: 'Next', has: page.locator('.enabled') }) で「Next」というテキストを持ち、かつクラス名が.enabledのボタンを絞り込む
await page
  .getByRole("button")
  .filter({ hasText: "/Next/", has: page.locator(".enabled") })
  .click();
GitHubで編集を提案

Discussion