|
| 1 | +import asyncio |
| 2 | + |
| 3 | +# Camoufox is external package and needs to be installed. It is not included in crawlee. |
| 4 | +from camoufox import AsyncNewBrowser |
| 5 | +from typing_extensions import override |
| 6 | + |
| 7 | +from crawlee.browsers import BrowserPool, PlaywrightBrowserController, PlaywrightBrowserPlugin |
| 8 | +from crawlee.playwright_crawler import PlaywrightCrawler, PlaywrightCrawlingContext |
| 9 | + |
| 10 | + |
| 11 | +class CamoufoxPlugin(PlaywrightBrowserPlugin): |
| 12 | + """Example browser plugin that uses Camoufox browser, but otherwise keeps the functionality of |
| 13 | + PlaywrightBrowserPlugin.""" |
| 14 | + |
| 15 | + @override |
| 16 | + async def new_browser(self) -> PlaywrightBrowserController: |
| 17 | + if not self._playwright: |
| 18 | + raise RuntimeError('Playwright browser plugin is not initialized.') |
| 19 | + |
| 20 | + return PlaywrightBrowserController( |
| 21 | + browser=await AsyncNewBrowser(self._playwright, headless=True, **self._browser_options), |
| 22 | + max_open_pages_per_browser=1, # Increase, if camoufox can handle it in your use case. |
| 23 | + header_generator=None, # This turns off the crawlee header_generation. Camoufox has its own. |
| 24 | + ) |
| 25 | + |
| 26 | + |
| 27 | +async def main() -> None: |
| 28 | + crawler = PlaywrightCrawler( |
| 29 | + # Limit the crawl to max requests. Remove or increase it for crawling all links. |
| 30 | + max_requests_per_crawl=10, |
| 31 | + # Custom browser pool. This gives users full control over browsers used by the crawler. |
| 32 | + browser_pool=BrowserPool(plugins=[CamoufoxPlugin()]), |
| 33 | + ) |
| 34 | + |
| 35 | + # Define the default request handler, which will be called for every request. |
| 36 | + @crawler.router.default_handler |
| 37 | + async def request_handler(context: PlaywrightCrawlingContext) -> None: |
| 38 | + context.log.info(f'Processing {context.request.url} ...') |
| 39 | + |
| 40 | + # Extract some data from the page using Playwright's API. |
| 41 | + posts = await context.page.query_selector_all('.athing') |
| 42 | + for post in posts: |
| 43 | + # Get the HTML elements for the title and rank within each post. |
| 44 | + title_element = await post.query_selector('.title a') |
| 45 | + |
| 46 | + # Extract the data we want from the elements. |
| 47 | + title = await title_element.inner_text() if title_element else None |
| 48 | + |
| 49 | + # Push the extracted data to the default dataset. |
| 50 | + await context.push_data({'title': title}) |
| 51 | + |
| 52 | + # Find a link to the next page and enqueue it if it exists. |
| 53 | + await context.enqueue_links(selector='.morelink') |
| 54 | + |
| 55 | + # Run the crawler with the initial list of URLs. |
| 56 | + await crawler.run(['https://news.ycombinator.com/']) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + asyncio.run(main()) |
0 commit comments