0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Playwright】Locator取得の逆引きメモ

Posted at

はじめに

Locator取得する際に、個人的によく使うものを逆引きメモでまとめました。
Locatorの詳細については、公式(Locators | Playwright)を参照ください。
気になった点など随時更新予定です。

role属性で取得する

基本的にrole属性で取得できるものはrole属性で取得する。
Playwright公式でも推奨されている。

サンプルHTML

sample.html
<input type="text" name="user-name" placeholder="ユーザー名を入力" maxlength="50" class="user-name" id="user-name-input">
<button>検索</button>

サンプルテスト

sample.spec.ts
let input = await page.getByRole("textbox", { name: "ユーザー名を入力" });
let button = await page.getByRole("button", { name: "検索" });

アクセシブル名はデバッグツールで確認できる。下記参考。
アクセシビリティツリー[AOM]について調べてみた

参考:getByRole | Playwright

textの値でLocatorを取得する

サンプルHTML

sample.html
<input type="text" name="user-name" placeholder="ユーザー名を入力" maxlength="50" class="user-name" id="user-name-input">
<button>検索</button>

サンプルテスト

sample.spec.ts
let button = await page.getByText("検索");

placeholderの値でLocatorを取得する

サンプルHTML

sample.html
<input type="text" name="user-name" placeholder="ユーザー名を入力" maxlength="50" class="user-name" id="user-name-input">

サンプルテスト

sample.spec.ts
let input = await page.getByPlaceholder('ユーザー名を入力');

セレクタでLocatorを取得する

サンプルHTML

sample.html
<input type="text" name="user-name" placeholder="ユーザー名を入力" maxlength="50" class="user-name" id="user-name-input">

class名で取得する

sample.spec.ts
let userNameInput = await page.locator(".user-name");

idで取得する

sample.spec.ts
let userNameInput = await page.locator("#user-name-input");

属性セレクタで取得する

sample.spec.ts
 let userNameInput = await page.locator('input[id="user-name-input"]');

対象Locatorを子として持つ要素を取得する

.filter()を使用して、対象Locatorを子として持つ要素を取得できる。

参考:Other locators | Playwright

例:「Hello」を表示しているlabelを子に持つlistitemを取得する

サンプルHTML

sample.html
<li><label>Hello</label></li>
<li><label>World</label></li>

サンプルテスト

sample.spec.ts
const child = await page.getByText('Hello', { exact: true });
const parent = await page.getByRole('listitem').filter({ has: child });
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?