拡張性
カスタムセレクターエンジン
Playwrightは、`selectors.register()` で登録されたカスタムセレクターエンジンをサポートしています。
セレクターエンジンは次のプロパティを持つ必要があります
- `query` 関数は、`root` を基準として `selector` に一致する最初の要素をクエリします。
- `queryAll` 関数は、`root` を基準として `selector` に一致するすべての要素をクエリします。
デフォルトでは、エンジンはフレームのJavaScriptコンテキストで直接実行され、たとえば、アプリケーション定義の関数を呼び出すことができます。エンジンをフレーム内のJavaScriptから分離しつつ、DOMへのアクセスを残すには、`{contentScript: true}` オプションでエンジンを登録します。コンテンツスクリプトエンジンは、`Node.prototype` メソッドの変更など、グローバルオブジェクトへの改ざんから保護されるため、より安全です。すべての組み込みセレクターエンジンはコンテンツスクリプトとして実行されます。他のカスタムエンジンと一緒に使用する場合、コンテンツスクリプトとして実行されることは保証されないことに注意してください。
セレクターはページを作成する前に登録する必要があります。
タグ名に基づいて要素をクエリするセレクターエンジンの登録例
- 同期
- 非同期
tag_selector = """
// 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));
}
}"""
# register the engine. selectors will be prefixed with "tag=".
playwright.selectors.register("tag", tag_selector)
# now we can use "tag=" selectors.
button = page.locator("tag=button")
button.click()
# we can combine it with built-in locators.
page.locator("tag=div").get_by_text("click me").click()
# we can use it in any methods supporting selectors.
button_count = page.locator("tag=button").count()
tag_selector = """
// 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));
}
}"""
# register the engine. selectors will be prefixed with "tag=".
await playwright.selectors.register("tag", tag_selector)
# now we can use "tag=" selectors.
button = page.locator("tag=button")
await button.click()
# we can combine it with built-in locators.
await page.locator("tag=div").get_by_text("click me").click()
# we can use it in any methods supporting selectors.
button_count = await page.locator("tag=button").count()