🎭

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

に公開
2026/09/24

🌱 はじめに

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

🌱 結論

🌱 1. 特定のテキストを含む: { hasText: テキスト }

// getByRole('button') でページ上のすべてのボタンを取得
// filter({ hasText: 'Login' }) で「Login」というテキストを含むボタンに絞り込む
// そのボタンをクリック
await page.getByRole("button").filter({ hasText: "Login" }).click();

🌱 2. 特定のテキストを含まない: { hasNotText: テキスト }

// getByRole('button') でページ上のすべてのボタンを取得
// filter({ hasNotText: 'Login' }) で「Login」というテキストを含まないボタンに絞り込む
// そのボタンをクリック
await page.getByRole("button").filter({ hasNotText: "Login" }).click();

🌱 3. 特定の要素を含む: { has: ロケーター }

has は、要素の属性ではなく、子孫要素がロケーターに一致するかで絞り込みます。

// getByRole('listitem') でリストの項目を取得
// filter({ has: page.getByRole('button', { name: '削除' }) }) で「削除」ボタンを含む項目に絞り込む
await page
  .getByRole("listitem")
  .filter({ has: page.getByRole("button", { name: "削除" }) });

🌱 4. 特定の要素を含まない: { hasNot: ロケーター }

// getByRole('listitem') でリストの項目を取得
// filter({ hasNot: page.getByRole('button', { name: '削除' }) }) で「削除」ボタンを含まない項目に絞り込む
await page
  .getByRole("listitem")
  .filter({ hasNot: page.getByRole("button", { name: "削除" }) });

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

// getByRole('listitem') でリストの項目を取得
// filter({ hasText: 'Next', has: page.locator('.enabled') }) で「Next」というテキストを含み、
// かつ enabled クラスを持つ子孫要素を含む項目に絞り込む
await page
  .getByRole("listitem")
  .filter({ hasText: "Next", has: page.locator(".enabled") })
  .click();
GitHubで編集を提案

Discussion