メインコンテンツへスキップ

拡張性

カスタムセレクターエンジン

Playwrightは、Selectors.RegisterAsync()で登録されたカスタムセレクターエンジンをサポートしています。

セレクターエンジンは以下のプロパティを持つ必要があります

  • `root`を基準として`selector`に一致する最初の要素をクエリする`query`関数。
  • `root`を基準として`selector`に一致するすべての要素をクエリする`queryAll`関数。

デフォルトでは、エンジンはフレームのJavaScriptコンテキストで直接実行され、例えばアプリケーション定義の関数を呼び出すことができます。フレーム内のJavaScriptからエンジンを分離しつつ、DOMへのアクセスを維持するには、`{contentScript: true}`オプションでエンジンを登録します。コンテンツスクリプトエンジンは、例えば`Node.prototype`メソッドの変更など、グローバルオブジェクトへの改ざんから保護されているため、より安全です。すべての組み込みセレクターエンジンはコンテンツスクリプトとして実行されます。他のカスタムエンジンと一緒に使用される場合、コンテンツスクリプトとして実行されることは保証されないことに注意してください。

セレクターはページを作成する前に登録する必要があります。

タグ名に基づいて要素をクエリするセレクターエンジンの登録例

// Register the engine. Selectors will be prefixed with "tag=".
// The script is evaluated in the page context.
await playwright.Selectors.Register("tag", new() {
Script = @"
// Must evaluate to a selector engine instance.
{
// Returns the first element matching given selector in the root's subtree.
query(root, selector) {
return root.querySelector(selector);
},

// Returns all elements matching given selector in the root's subtree.
queryAll(root, selector) {
return Array.from(root.querySelectorAll(selector));
}
}"
});

// Now we can use "tag=" selectors.
await page.Locator("tag=button").ClickAsync();

// We can combine it with built-in locators.
await page.Locator("tag=div").GetByText("Click me").ClickAsync();