File size: 32,565 Bytes
03c0888
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6yLvrXn7yZQI"
      },
      "source": [
        "# Crawl4AI: Advanced Web Crawling and Data Extraction\n",
        "\n",
        "Welcome to this interactive notebook showcasing Crawl4AI, an advanced asynchronous web crawling and data extraction library.\n",
        "\n",
        "- GitHub Repository: [https://github.com/unclecode/crawl4ai](https://github.com/unclecode/crawl4ai)\n",
        "- Twitter: [@unclecode](https://twitter.com/unclecode)\n",
        "- Website: [https://crawl4ai.com](https://crawl4ai.com)\n",
        "\n",
        "Let's explore the powerful features of Crawl4AI!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KIn_9nxFyZQK"
      },
      "source": [
        "## Installation\n",
        "\n",
        "First, let's install Crawl4AI from GitHub:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mSnaxLf3zMog"
      },
      "outputs": [],
      "source": [
        "!sudo apt-get update && sudo apt-get install -y libwoff1 libopus0 libwebp6 libwebpdemux2 libenchant1c2a libgudev-1.0-0 libsecret-1-0 libhyphen0 libgdk-pixbuf2.0-0 libegl1 libnotify4 libxslt1.1 libevent-2.1-7 libgles2 libvpx6 libxcomposite1 libatk1.0-0 libatk-bridge2.0-0 libepoxy0 libgtk-3-0 libharfbuzz-icu0"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xlXqaRtayZQK"
      },
      "outputs": [],
      "source": [
        "!pip install crawl4ai\n",
        "!pip install nest-asyncio\n",
        "!playwright install"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qKCE7TI7yZQL"
      },
      "source": [
        "Now, let's import the necessary libraries:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "I67tr7aAyZQL"
      },
      "outputs": [],
      "source": [
        "import asyncio\n",
        "import nest_asyncio\n",
        "from crawl4ai import AsyncWebCrawler\n",
        "from crawl4ai.extraction_strategy import JsonCssExtractionStrategy, LLMExtractionStrategy\n",
        "import json\n",
        "import time\n",
        "from pydantic import BaseModel, Field\n",
        "\n",
        "nest_asyncio.apply()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "h7yR_Rt_yZQM"
      },
      "source": [
        "## Basic Usage\n",
        "\n",
        "Let's start with a simple crawl example:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "yBh6hf4WyZQM",
        "outputId": "0f83af5c-abba-4175-ed95-70b7512e6bcc"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[LOG] 🌀️  Warming up the AsyncWebCrawler\n",
            "[LOG] 🌞 AsyncWebCrawler is ready to crawl\n",
            "[LOG] πŸš€ Content extracted for https://www.nbcnews.com/business, success: True, time taken: 0.05 seconds\n",
            "[LOG] πŸš€ Extraction done for https://www.nbcnews.com/business, time taken: 0.05 seconds.\n",
            "18102\n"
          ]
        }
      ],
      "source": [
        "async def simple_crawl():\n",
        "    async with AsyncWebCrawler(verbose=True) as crawler:\n",
        "        result = await crawler.arun(url=\"https://www.nbcnews.com/business\")\n",
        "        print(len(result.markdown))\n",
        "await simple_crawl()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9rtkgHI28uI4"
      },
      "source": [
        "πŸ’‘ By default, **Crawl4AI** caches the result of every URL, so the next time you call it, you’ll get an instant result. But if you want to bypass the cache, just set `bypass_cache=True`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MzZ0zlJ9yZQM"
      },
      "source": [
        "## Advanced Features\n",
        "\n",
        "### Executing JavaScript and Using CSS Selectors"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "gHStF86xyZQM",
        "outputId": "34d0fb6d-4dec-4677-f76e-85a1f082829b"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[LOG] 🌀️  Warming up the AsyncWebCrawler\n",
            "[LOG] 🌞 AsyncWebCrawler is ready to crawl\n",
            "[LOG] πŸ•ΈοΈ Crawling https://www.nbcnews.com/business using AsyncPlaywrightCrawlerStrategy...\n",
            "[LOG] βœ… Crawled https://www.nbcnews.com/business successfully!\n",
            "[LOG] πŸš€ Crawling done for https://www.nbcnews.com/business, success: True, time taken: 6.06 seconds\n",
            "[LOG] πŸš€ Content extracted for https://www.nbcnews.com/business, success: True, time taken: 0.10 seconds\n",
            "[LOG] πŸ”₯ Extracting semantic blocks for https://www.nbcnews.com/business, Strategy: AsyncWebCrawler\n",
            "[LOG] πŸš€ Extraction done for https://www.nbcnews.com/business, time taken: 0.11 seconds.\n",
            "41135\n"
          ]
        }
      ],
      "source": [
        "async def js_and_css():\n",
        "    async with AsyncWebCrawler(verbose=True) as crawler:\n",
        "        js_code = [\"const loadMoreButton = Array.from(document.querySelectorAll('button')).find(button => button.textContent.includes('Load More')); loadMoreButton && loadMoreButton.click();\"]\n",
        "        result = await crawler.arun(\n",
        "            url=\"https://www.nbcnews.com/business\",\n",
        "            js_code=js_code,\n",
        "            # css_selector=\"YOUR_CSS_SELECTOR_HERE\",\n",
        "            bypass_cache=True\n",
        "        )\n",
        "        print(len(result.markdown))\n",
        "\n",
        "await js_and_css()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cqE_W4coyZQM"
      },
      "source": [
        "### Using a Proxy\n",
        "\n",
        "Note: You'll need to replace the proxy URL with a working proxy for this example to run successfully."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QjAyiAGqyZQM"
      },
      "outputs": [],
      "source": [
        "async def use_proxy():\n",
        "    async with AsyncWebCrawler(verbose=True, proxy=\"http://your-proxy-url:port\") as crawler:\n",
        "        result = await crawler.arun(\n",
        "            url=\"https://www.nbcnews.com/business\",\n",
        "            bypass_cache=True\n",
        "        )\n",
        "        print(result.markdown[:500])  # Print first 500 characters\n",
        "\n",
        "# Uncomment the following line to run the proxy example\n",
        "# await use_proxy()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XTZ88lbayZQN"
      },
      "source": [
        "### Extracting Structured Data with OpenAI\n",
        "\n",
        "Note: You'll need to set your OpenAI API key as an environment variable for this example to work."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "fIOlDayYyZQN",
        "outputId": "cb8359cc-dee0-4762-9698-5dfdcee055b8"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[LOG] 🌀️  Warming up the AsyncWebCrawler\n",
            "[LOG] 🌞 AsyncWebCrawler is ready to crawl\n",
            "[LOG] πŸ•ΈοΈ Crawling https://openai.com/api/pricing/ using AsyncPlaywrightCrawlerStrategy...\n",
            "[LOG] βœ… Crawled https://openai.com/api/pricing/ successfully!\n",
            "[LOG] πŸš€ Crawling done for https://openai.com/api/pricing/, success: True, time taken: 3.77 seconds\n",
            "[LOG] πŸš€ Content extracted for https://openai.com/api/pricing/, success: True, time taken: 0.21 seconds\n",
            "[LOG] πŸ”₯ Extracting semantic blocks for https://openai.com/api/pricing/, Strategy: AsyncWebCrawler\n",
            "[LOG] Call LLM for https://openai.com/api/pricing/ - block index: 0\n",
            "[LOG] Call LLM for https://openai.com/api/pricing/ - block index: 1\n",
            "[LOG] Call LLM for https://openai.com/api/pricing/ - block index: 2\n",
            "[LOG] Call LLM for https://openai.com/api/pricing/ - block index: 3\n",
            "[LOG] Extracted 4 blocks from URL: https://openai.com/api/pricing/ block index: 3\n",
            "[LOG] Call LLM for https://openai.com/api/pricing/ - block index: 4\n",
            "[LOG] Extracted 5 blocks from URL: https://openai.com/api/pricing/ block index: 0\n",
            "[LOG] Extracted 1 blocks from URL: https://openai.com/api/pricing/ block index: 4\n",
            "[LOG] Extracted 8 blocks from URL: https://openai.com/api/pricing/ block index: 1\n",
            "[LOG] Extracted 12 blocks from URL: https://openai.com/api/pricing/ block index: 2\n",
            "[LOG] πŸš€ Extraction done for https://openai.com/api/pricing/, time taken: 8.55 seconds.\n",
            "5029\n"
          ]
        }
      ],
      "source": [
        "import os\n",
        "from google.colab import userdata\n",
        "os.environ['OPENAI_API_KEY'] = userdata.get('OPENAI_API_KEY')\n",
        "\n",
        "class OpenAIModelFee(BaseModel):\n",
        "    model_name: str = Field(..., description=\"Name of the OpenAI model.\")\n",
        "    input_fee: str = Field(..., description=\"Fee for input token for the OpenAI model.\")\n",
        "    output_fee: str = Field(..., description=\"Fee for output token for the OpenAI model.\")\n",
        "\n",
        "async def extract_openai_fees():\n",
        "    async with AsyncWebCrawler(verbose=True) as crawler:\n",
        "        result = await crawler.arun(\n",
        "            url='https://openai.com/api/pricing/',\n",
        "            word_count_threshold=1,\n",
        "            extraction_strategy=LLMExtractionStrategy(\n",
        "                provider=\"openai/gpt-4o\", api_token=os.getenv('OPENAI_API_KEY'),\n",
        "                schema=OpenAIModelFee.schema(),\n",
        "                extraction_type=\"schema\",\n",
        "                instruction=\"\"\"From the crawled content, extract all mentioned model names along with their fees for input and output tokens.\n",
        "                Do not miss any models in the entire content. One extracted model JSON format should look like this:\n",
        "                {\"model_name\": \"GPT-4\", \"input_fee\": \"US$10.00 / 1M tokens\", \"output_fee\": \"US$30.00 / 1M tokens\"}.\"\"\"\n",
        "            ),\n",
        "            bypass_cache=True,\n",
        "        )\n",
        "        print(len(result.extracted_content))\n",
        "\n",
        "# Uncomment the following line to run the OpenAI extraction example\n",
        "await extract_openai_fees()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BypA5YxEyZQN"
      },
      "source": [
        "### Advanced Multi-Page Crawling with JavaScript Execution"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tfkcVQ0b7mw-"
      },
      "source": [
        "## Advanced Multi-Page Crawling with JavaScript Execution\n",
        "\n",
        "This example demonstrates Crawl4AI's ability to handle complex crawling scenarios, specifically extracting commits from multiple pages of a GitHub repository. The challenge here is that clicking the \"Next\" button doesn't load a new page, but instead uses asynchronous JavaScript to update the content. This is a common hurdle in modern web crawling.\n",
        "\n",
        "To overcome this, we use Crawl4AI's custom JavaScript execution to simulate clicking the \"Next\" button, and implement a custom hook to detect when new data has loaded. Our strategy involves comparing the first commit's text before and after \"clicking\" Next, waiting until it changes to confirm new data has rendered. This showcases Crawl4AI's flexibility in handling dynamic content and its ability to implement custom logic for even the most challenging crawling tasks."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "qUBKGpn3yZQN",
        "outputId": "3e555b6a-ed33-42f4-cce9-499a923fbe17"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[LOG] 🌀️  Warming up the AsyncWebCrawler\n",
            "[LOG] 🌞 AsyncWebCrawler is ready to crawl\n",
            "[LOG] πŸ•ΈοΈ Crawling https://github.com/microsoft/TypeScript/commits/main using AsyncPlaywrightCrawlerStrategy...\n",
            "[LOG] βœ… Crawled https://github.com/microsoft/TypeScript/commits/main successfully!\n",
            "[LOG] πŸš€ Crawling done for https://github.com/microsoft/TypeScript/commits/main, success: True, time taken: 5.16 seconds\n",
            "[LOG] πŸš€ Content extracted for https://github.com/microsoft/TypeScript/commits/main, success: True, time taken: 0.28 seconds\n",
            "[LOG] πŸ”₯ Extracting semantic blocks for https://github.com/microsoft/TypeScript/commits/main, Strategy: AsyncWebCrawler\n",
            "[LOG] πŸš€ Extraction done for https://github.com/microsoft/TypeScript/commits/main, time taken: 0.28 seconds.\n",
            "Page 1: Found 35 commits\n",
            "[LOG] πŸ•ΈοΈ Crawling https://github.com/microsoft/TypeScript/commits/main using AsyncPlaywrightCrawlerStrategy...\n",
            "[LOG] βœ… Crawled https://github.com/microsoft/TypeScript/commits/main successfully!\n",
            "[LOG] πŸš€ Crawling done for https://github.com/microsoft/TypeScript/commits/main, success: True, time taken: 0.78 seconds\n",
            "[LOG] πŸš€ Content extracted for https://github.com/microsoft/TypeScript/commits/main, success: True, time taken: 0.90 seconds\n",
            "[LOG] πŸ”₯ Extracting semantic blocks for https://github.com/microsoft/TypeScript/commits/main, Strategy: AsyncWebCrawler\n",
            "[LOG] πŸš€ Extraction done for https://github.com/microsoft/TypeScript/commits/main, time taken: 0.90 seconds.\n",
            "Page 2: Found 35 commits\n",
            "[LOG] πŸ•ΈοΈ Crawling https://github.com/microsoft/TypeScript/commits/main using AsyncPlaywrightCrawlerStrategy...\n",
            "[LOG] βœ… Crawled https://github.com/microsoft/TypeScript/commits/main successfully!\n",
            "[LOG] πŸš€ Crawling done for https://github.com/microsoft/TypeScript/commits/main, success: True, time taken: 2.00 seconds\n",
            "[LOG] πŸš€ Content extracted for https://github.com/microsoft/TypeScript/commits/main, success: True, time taken: 0.74 seconds\n",
            "[LOG] πŸ”₯ Extracting semantic blocks for https://github.com/microsoft/TypeScript/commits/main, Strategy: AsyncWebCrawler\n",
            "[LOG] πŸš€ Extraction done for https://github.com/microsoft/TypeScript/commits/main, time taken: 0.75 seconds.\n",
            "Page 3: Found 35 commits\n",
            "Successfully crawled 105 commits across 3 pages\n"
          ]
        }
      ],
      "source": [
        "import re\n",
        "from bs4 import BeautifulSoup\n",
        "\n",
        "async def crawl_typescript_commits():\n",
        "    first_commit = \"\"\n",
        "    async def on_execution_started(page):\n",
        "        nonlocal first_commit\n",
        "        try:\n",
        "            while True:\n",
        "                await page.wait_for_selector('li.Box-sc-g0xbh4-0 h4')\n",
        "                commit = await page.query_selector('li.Box-sc-g0xbh4-0 h4')\n",
        "                commit = await commit.evaluate('(element) => element.textContent')\n",
        "                commit = re.sub(r'\\s+', '', commit)\n",
        "                if commit and commit != first_commit:\n",
        "                    first_commit = commit\n",
        "                    break\n",
        "                await asyncio.sleep(0.5)\n",
        "        except Exception as e:\n",
        "            print(f\"Warning: New content didn't appear after JavaScript execution: {e}\")\n",
        "\n",
        "    async with AsyncWebCrawler(verbose=True) as crawler:\n",
        "        crawler.crawler_strategy.set_hook('on_execution_started', on_execution_started)\n",
        "\n",
        "        url = \"https://github.com/microsoft/TypeScript/commits/main\"\n",
        "        session_id = \"typescript_commits_session\"\n",
        "        all_commits = []\n",
        "\n",
        "        js_next_page = \"\"\"\n",
        "        const button = document.querySelector('a[data-testid=\"pagination-next-button\"]');\n",
        "        if (button) button.click();\n",
        "        \"\"\"\n",
        "\n",
        "        for page in range(3):  # Crawl 3 pages\n",
        "            result = await crawler.arun(\n",
        "                url=url,\n",
        "                session_id=session_id,\n",
        "                css_selector=\"li.Box-sc-g0xbh4-0\",\n",
        "                js=js_next_page if page > 0 else None,\n",
        "                bypass_cache=True,\n",
        "                js_only=page > 0\n",
        "            )\n",
        "\n",
        "            assert result.success, f\"Failed to crawl page {page + 1}\"\n",
        "\n",
        "            soup = BeautifulSoup(result.cleaned_html, 'html.parser')\n",
        "            commits = soup.select(\"li\")\n",
        "            all_commits.extend(commits)\n",
        "\n",
        "            print(f\"Page {page + 1}: Found {len(commits)} commits\")\n",
        "\n",
        "        await crawler.crawler_strategy.kill_session(session_id)\n",
        "        print(f\"Successfully crawled {len(all_commits)} commits across 3 pages\")\n",
        "\n",
        "await crawl_typescript_commits()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EJRnYsp6yZQN"
      },
      "source": [
        "### Using JsonCssExtractionStrategy for Fast Structured Output"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1ZMqIzB_8SYp"
      },
      "source": [
        "The JsonCssExtractionStrategy is a powerful feature of Crawl4AI that allows for precise, structured data extraction from web pages. Here's how it works:\n",
        "\n",
        "1. You define a schema that describes the pattern of data you're interested in extracting.\n",
        "2. The schema includes a base selector that identifies repeating elements on the page.\n",
        "3. Within the schema, you define fields, each with its own selector and type.\n",
        "4. These field selectors are applied within the context of each base selector element.\n",
        "5. The strategy supports nested structures, lists within lists, and various data types.\n",
        "6. You can even include computed fields for more complex data manipulation.\n",
        "\n",
        "This approach allows for highly flexible and precise data extraction, transforming semi-structured web content into clean, structured JSON data. It's particularly useful for extracting consistent data patterns from pages like product listings, news articles, or search results.\n",
        "\n",
        "For more details and advanced usage, check out the full documentation on the Crawl4AI website."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "trCMR2T9yZQN",
        "outputId": "718d36f4-cccf-40f4-8d8c-c3ba73524d16"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[LOG] 🌀️  Warming up the AsyncWebCrawler\n",
            "[LOG] 🌞 AsyncWebCrawler is ready to crawl\n",
            "[LOG] πŸ•ΈοΈ Crawling https://www.nbcnews.com/business using AsyncPlaywrightCrawlerStrategy...\n",
            "[LOG] βœ… Crawled https://www.nbcnews.com/business successfully!\n",
            "[LOG] πŸš€ Crawling done for https://www.nbcnews.com/business, success: True, time taken: 7.00 seconds\n",
            "[LOG] πŸš€ Content extracted for https://www.nbcnews.com/business, success: True, time taken: 0.32 seconds\n",
            "[LOG] πŸ”₯ Extracting semantic blocks for https://www.nbcnews.com/business, Strategy: AsyncWebCrawler\n",
            "[LOG] πŸš€ Extraction done for https://www.nbcnews.com/business, time taken: 0.48 seconds.\n",
            "Successfully extracted 11 news teasers\n",
            "{\n",
            "  \"category\": \"Business News\",\n",
            "  \"headline\": \"NBC ripped up its Olympics playbook for 2024 \\u2014 so far, the new strategy paid off\",\n",
            "  \"summary\": \"The Olympics have long been key to NBCUniversal. Paris marked the 18th Olympic Games broadcast by NBC in the U.S.\",\n",
            "  \"time\": \"13h ago\",\n",
            "  \"image\": {\n",
            "    \"src\": \"https://media-cldnry.s-nbcnews.com/image/upload/t_focal-200x100,f_auto,q_auto:best/rockcms/2024-09/240903-nbc-olympics-ch-1344-c7a486.jpg\",\n",
            "    \"alt\": \"Mike Tirico.\"\n",
            "  },\n",
            "  \"link\": \"https://www.nbcnews.com/business\"\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "async def extract_news_teasers():\n",
        "    schema = {\n",
        "        \"name\": \"News Teaser Extractor\",\n",
        "        \"baseSelector\": \".wide-tease-item__wrapper\",\n",
        "        \"fields\": [\n",
        "            {\n",
        "                \"name\": \"category\",\n",
        "                \"selector\": \".unibrow span[data-testid='unibrow-text']\",\n",
        "                \"type\": \"text\",\n",
        "            },\n",
        "            {\n",
        "                \"name\": \"headline\",\n",
        "                \"selector\": \".wide-tease-item__headline\",\n",
        "                \"type\": \"text\",\n",
        "            },\n",
        "            {\n",
        "                \"name\": \"summary\",\n",
        "                \"selector\": \".wide-tease-item__description\",\n",
        "                \"type\": \"text\",\n",
        "            },\n",
        "            {\n",
        "                \"name\": \"time\",\n",
        "                \"selector\": \"[data-testid='wide-tease-date']\",\n",
        "                \"type\": \"text\",\n",
        "            },\n",
        "            {\n",
        "                \"name\": \"image\",\n",
        "                \"type\": \"nested\",\n",
        "                \"selector\": \"picture.teasePicture img\",\n",
        "                \"fields\": [\n",
        "                    {\"name\": \"src\", \"type\": \"attribute\", \"attribute\": \"src\"},\n",
        "                    {\"name\": \"alt\", \"type\": \"attribute\", \"attribute\": \"alt\"},\n",
        "                ],\n",
        "            },\n",
        "            {\n",
        "                \"name\": \"link\",\n",
        "                \"selector\": \"a[href]\",\n",
        "                \"type\": \"attribute\",\n",
        "                \"attribute\": \"href\",\n",
        "            },\n",
        "        ],\n",
        "    }\n",
        "\n",
        "    extraction_strategy = JsonCssExtractionStrategy(schema, verbose=True)\n",
        "\n",
        "    async with AsyncWebCrawler(verbose=True) as crawler:\n",
        "        result = await crawler.arun(\n",
        "            url=\"https://www.nbcnews.com/business\",\n",
        "            extraction_strategy=extraction_strategy,\n",
        "            bypass_cache=True,\n",
        "        )\n",
        "\n",
        "        assert result.success, \"Failed to crawl the page\"\n",
        "\n",
        "        news_teasers = json.loads(result.extracted_content)\n",
        "        print(f\"Successfully extracted {len(news_teasers)} news teasers\")\n",
        "        print(json.dumps(news_teasers[0], indent=2))\n",
        "\n",
        "await extract_news_teasers()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FnyVhJaByZQN"
      },
      "source": [
        "## Speed Comparison\n",
        "\n",
        "Let's compare the speed of Crawl4AI with Firecrawl, a paid service. Note that we can't run Firecrawl in this Colab environment, so we'll simulate its performance based on previously recorded data."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "agDD186f3wig"
      },
      "source": [
        "πŸ’‘ **Note on Speed Comparison:**\n",
        "\n",
        "The speed test conducted here is running on Google Colab, where the internet speed and performance can vary and may not reflect optimal conditions. When we call Firecrawl's API, we're seeing its best performance, while Crawl4AI's performance is limited by Colab's network speed.\n",
        "\n",
        "For a more accurate comparison, it's recommended to run these tests on your own servers or computers with a stable and fast internet connection. Despite these limitations, Crawl4AI still demonstrates faster performance in this environment.\n",
        "\n",
        "If you run these tests locally, you may observe an even more significant speed advantage for Crawl4AI compared to other services."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "F7KwHv8G1LbY"
      },
      "outputs": [],
      "source": [
        "!pip install firecrawl"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "91813zILyZQN",
        "outputId": "663223db-ab89-4976-b233-05ceca62b19b"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Firecrawl (simulated):\n",
            "Time taken: 4.38 seconds\n",
            "Content length: 41967 characters\n",
            "Images found: 49\n",
            "\n",
            "Crawl4AI (simple crawl):\n",
            "Time taken: 4.22 seconds\n",
            "Content length: 18221 characters\n",
            "Images found: 49\n",
            "\n",
            "Crawl4AI (with JavaScript execution):\n",
            "Time taken: 9.13 seconds\n",
            "Content length: 34243 characters\n",
            "Images found: 89\n"
          ]
        }
      ],
      "source": [
        "import os\n",
        "from google.colab import userdata\n",
        "os.environ['FIRECRAWL_API_KEY'] = userdata.get('FIRECRAWL_API_KEY')\n",
        "import time\n",
        "from firecrawl import FirecrawlApp\n",
        "\n",
        "async def speed_comparison():\n",
        "    # Simulated Firecrawl performance\n",
        "    app = FirecrawlApp(api_key=os.environ['FIRECRAWL_API_KEY'])\n",
        "    start = time.time()\n",
        "    scrape_status = app.scrape_url(\n",
        "    'https://www.nbcnews.com/business',\n",
        "    params={'formats': ['markdown', 'html']}\n",
        "    )\n",
        "    end = time.time()\n",
        "    print(\"Firecrawl (simulated):\")\n",
        "    print(f\"Time taken: {end - start:.2f} seconds\")\n",
        "    print(f\"Content length: {len(scrape_status['markdown'])} characters\")\n",
        "    print(f\"Images found: {scrape_status['markdown'].count('cldnry.s-nbcnews.com')}\")\n",
        "    print()\n",
        "\n",
        "    async with AsyncWebCrawler() as crawler:\n",
        "        # Crawl4AI simple crawl\n",
        "        start = time.time()\n",
        "        result = await crawler.arun(\n",
        "            url=\"https://www.nbcnews.com/business\",\n",
        "            word_count_threshold=0,\n",
        "            bypass_cache=True,\n",
        "            verbose=False\n",
        "        )\n",
        "        end = time.time()\n",
        "        print(\"Crawl4AI (simple crawl):\")\n",
        "        print(f\"Time taken: {end - start:.2f} seconds\")\n",
        "        print(f\"Content length: {len(result.markdown)} characters\")\n",
        "        print(f\"Images found: {result.markdown.count('cldnry.s-nbcnews.com')}\")\n",
        "        print()\n",
        "\n",
        "        # Crawl4AI with JavaScript execution\n",
        "        start = time.time()\n",
        "        result = await crawler.arun(\n",
        "            url=\"https://www.nbcnews.com/business\",\n",
        "            js_code=[\"const loadMoreButton = Array.from(document.querySelectorAll('button')).find(button => button.textContent.includes('Load More')); loadMoreButton && loadMoreButton.click();\"],\n",
        "            word_count_threshold=0,\n",
        "            bypass_cache=True,\n",
        "            verbose=False\n",
        "        )\n",
        "        end = time.time()\n",
        "        print(\"Crawl4AI (with JavaScript execution):\")\n",
        "        print(f\"Time taken: {end - start:.2f} seconds\")\n",
        "        print(f\"Content length: {len(result.markdown)} characters\")\n",
        "        print(f\"Images found: {result.markdown.count('cldnry.s-nbcnews.com')}\")\n",
        "\n",
        "await speed_comparison()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OBFFYVJIyZQN"
      },
      "source": [
        "If you run on a local machine with a proper internet speed:\n",
        "- Simple crawl: Crawl4AI is typically over 3-4 times faster than Firecrawl.\n",
        "- With JavaScript execution: Even when executing JavaScript to load more content (potentially doubling the number of images found), Crawl4AI is still faster than Firecrawl's simple crawl.\n",
        "\n",
        "Please note that actual performance may vary depending on network conditions and the specific content being crawled."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "A6_1RK1_yZQO"
      },
      "source": [
        "## Conclusion\n",
        "\n",
        "In this notebook, we've explored the powerful features of Crawl4AI, including:\n",
        "\n",
        "1. Basic crawling\n",
        "2. JavaScript execution and CSS selector usage\n",
        "3. Proxy support\n",
        "4. Structured data extraction with OpenAI\n",
        "5. Advanced multi-page crawling with JavaScript execution\n",
        "6. Fast structured output using JsonCssExtractionStrategy\n",
        "7. Speed comparison with other services\n",
        "\n",
        "Crawl4AI offers a fast, flexible, and powerful solution for web crawling and data extraction tasks. Its asynchronous architecture and advanced features make it suitable for a wide range of applications, from simple web scraping to complex, multi-page data extraction scenarios.\n",
        "\n",
        "For more information and advanced usage, please visit the [Crawl4AI documentation](https://crawl4ai.com/mkdocs/).\n",
        "\n",
        "Happy crawling!"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "venv",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.13"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}