From cd41c3429993d8dd42d82733cf1ec2153684090c Mon Sep 17 00:00:00 2001 From: Max Schmitt Date: Thu, 19 Aug 2021 21:01:40 +0200 Subject: [PATCH] docs(python): add missing register selector docs (#8309) --- docs/src/api/class-selectors.md | 70 ++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/docs/src/api/class-selectors.md b/docs/src/api/class-selectors.md index 0891a6876d..1cfa4617da 100644 --- a/docs/src/api/class-selectors.md +++ b/docs/src/api/class-selectors.md @@ -69,11 +69,77 @@ browser.close(); ``` ```python async -# FIXME: add snippet +import asyncio +from playwright.async_api import async_playwright + +async def run(playwright): + tag_selector = """ + { + // 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) + browser = await playwright.chromium.launch() + page = await browser.new_page() + await page.set_content('
') + + # Use the selector prefixed with its name. + button = await page.query_selector('tag=button') + # Combine it with other selector engines. + await page.click('tag=div >> text="Click me"') + # Can use it in any methods supporting selectors. + button_count = await page.eval_on_selector_all('tag=button', 'buttons => buttons.length') + print(button_count) + await browser.close() + +async def main(): + async with async_playwright() as playwright: + await run(playwright) + +asyncio.run(main()) ``` ```python sync -# FIXME: add snippet +from playwright.sync_api import sync_playwright + +def run(playwright): + tag_selector = """ + { + // 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) + browser = playwright.chromium.launch() + page = browser.new_page() + page.set_content('
') + + # Use the selector prefixed with its name. + button = page.query_selector('tag=button') + # Combine it with other selector engines. + page.click('tag=div >> text="Click me"') + # Can use it in any methods supporting selectors. + button_count = page.eval_on_selector_all('tag=button', 'buttons => buttons.length') + print(button_count) + browser.close() + +with sync_playwright() as playwright: + run(playwright) ``` ```csharp