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

拡張性

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

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();