|
| 1 | +"""Example: Customize pypecdp using OOP inheritance. |
| 2 | +
|
| 3 | +Demonstrates how to extend pypecdp classes with custom functionality. |
| 4 | +""" |
| 5 | + |
| 6 | +import asyncio |
| 7 | +import os |
| 8 | + |
| 9 | +from pypecdp import Browser, Elem, Tab, cdp |
| 10 | + |
| 11 | + |
| 12 | +# Custom Elem with additional methods |
| 13 | +class MyElem(Elem): |
| 14 | + """Custom element with click_and_wait method.""" |
| 15 | + |
| 16 | + async def click_and_wait(self, timeout: float = 10.0) -> None: |
| 17 | + """Click element and wait for navigation.""" |
| 18 | + tab = await self.click() |
| 19 | + if tab: |
| 20 | + await tab.wait_for_event(cdp.page.LoadEventFired, timeout=timeout) |
| 21 | + print(f"Navigated to: {tab.url}") |
| 22 | + |
| 23 | + |
| 24 | +# Custom Tab using custom Elem |
| 25 | +class MyTab(Tab): |
| 26 | + """Custom tab with helper methods.""" |
| 27 | + |
| 28 | + elem_class = MyElem # Use our custom Elem class |
| 29 | + |
| 30 | + async def get_title(self) -> str: |
| 31 | + """Get page title via JavaScript.""" |
| 32 | + result = await self.eval("document.title") |
| 33 | + return result.value if result.value else "" |
| 34 | + |
| 35 | + |
| 36 | +# Custom Browser using custom Tab |
| 37 | +class MyBrowser(Browser): |
| 38 | + """Custom browser with helper methods.""" |
| 39 | + |
| 40 | + tab_class = MyTab # Use our custom Tab class |
| 41 | + |
| 42 | + async def navigate_and_log(self, url: str) -> Tab: |
| 43 | + """Navigate with logging.""" |
| 44 | + print(f"Navigating to: {url}") |
| 45 | + tab = await self.navigate(url) |
| 46 | + print(f"Loaded: {url}") |
| 47 | + return tab |
| 48 | + |
| 49 | + |
| 50 | +async def main() -> None: |
| 51 | + """Demonstrate custom classes.""" |
| 52 | + # Use custom browser |
| 53 | + browser = await MyBrowser.start( |
| 54 | + chrome_path=os.environ.get("PYPECDP_CHROME_PATH", "chromium"), |
| 55 | + headless=True, |
| 56 | + ) |
| 57 | + |
| 58 | + # All tabs will be MyTab instances |
| 59 | + tab = await browser.navigate_and_log("https://example.com") |
| 60 | + print(f"Title: {await tab.get_title()}") |
| 61 | + |
| 62 | + # All elements will be MyElem instances |
| 63 | + link = await tab.wait_for_elem('a[href*="iana"]') |
| 64 | + if link: |
| 65 | + # Use custom click_and_wait method |
| 66 | + await link.click_and_wait() |
| 67 | + |
| 68 | + await browser.close() |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + asyncio.run(main()) |
0 commit comments