|
| 1 | +import asyncio |
| 2 | + |
1 | 3 | from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext |
2 | 4 |
|
3 | 5 |
|
4 | 6 | async def main() -> None: |
5 | 7 | crawler = PlaywrightCrawler( |
6 | 8 | max_requests_per_crawl=10, # Limit the max requests per crawl. |
7 | | - headless=False, # Show the browser window. |
8 | | - browser_type='firefox', # Use the Firefox browser. |
| 9 | + headless=True, # Run in headless mode (set to False to see the browser). |
| 10 | + browser_type='firefox', # Use Firefox browser. |
9 | 11 | ) |
10 | 12 |
|
11 | 13 | # Define the default request handler, which will be called for every request. |
12 | 14 | @crawler.router.default_handler |
13 | 15 | async def request_handler(context: PlaywrightCrawlingContext) -> None: |
14 | 16 | context.log.info(f'Processing {context.request.url} ...') |
15 | 17 |
|
16 | | - # Extract and enqueue all links found on the page. |
17 | | - await context.enqueue_links() |
18 | | - |
19 | 18 | # Extract data from the page using Playwright API. |
20 | 19 | data = { |
21 | 20 | 'url': context.request.url, |
22 | 21 | 'title': await context.page.title(), |
23 | | - 'content': (await context.page.content())[:100], |
24 | 22 | } |
25 | 23 |
|
26 | 24 | # Push the extracted data to the default dataset. |
27 | 25 | await context.push_data(data) |
28 | 26 |
|
| 27 | + # Extract all links on the page and enqueue them. |
| 28 | + await context.enqueue_links() |
| 29 | + |
29 | 30 | # Run the crawler with the initial list of URLs. |
30 | 31 | await crawler.run(['https://crawlee.dev']) |
31 | 32 |
|
32 | | - # Export the entire dataset to a JSON file. |
33 | | - await crawler.export_data('results.json') |
| 33 | + # Export the entire dataset to a CSV file. |
| 34 | + await crawler.export_data('results.csv') |
34 | 35 |
|
35 | | - # Or work with the data directly. |
| 36 | + # Or access the data directly. |
36 | 37 | data = await crawler.get_data() |
37 | 38 | crawler.log.info(f'Extracted data: {data.items}') |
| 39 | + |
| 40 | + |
| 41 | +if __name__ == '__main__': |
| 42 | + asyncio.run(main()) |
0 commit comments