示例与模板(2/3)

A comprehensive web-based tutorial for learning and experimenting with C4A-Script - Crawl4AI's visual web automation language.

🚀 Quick Start

Prerequisites

  • Python 3.7+
  • Modern web browser (Chrome, Firefox, Safari, Edge)

Running the Tutorial

  1. Clone and Navigate
git clone https://github.com/unclecode/crawl4ai.git
cd crawl4ai/docs/examples/c4a_script/tutorial/
  1. Install Dependencies
pip install -r requirements.txt
  1. Launch the Server
python server.py
  1. Open in Browser
http://localhost:8000

🌐 Try Online: Live Demo

2. Try Your First Script

# Basic interaction
GO playground/
WAIT `body` 2
IF (EXISTS `.cookie-banner`) THEN CLICK `.accept`
CLICK `#start-tutorial`

🎯 What You'll Learn

Core Features

  • 📝 Text Editor: Write C4A-Script with syntax highlighting
  • 🧩 Visual Editor: Build scripts using drag-and-drop Blockly interface
  • 🎬 Recording Mode: Capture browser actions and auto-generate scripts
  • ⚡ Live Execution: Run scripts in real-time with instant feedback
  • 📊 Timeline View: Visualize and edit automation steps

📚 Tutorial Content

Basic Commands

  • Navigation: GO url
  • Waiting: WAIT selector timeout or WAIT seconds
  • Clicking: CLICK selector
  • Typing: TYPE "text"
  • Scrolling: SCROLL DOWN/UP amount

Control Flow

  • Conditionals: IF (condition) THEN action
  • Loops: REPEAT (action, condition)
  • Procedures: Define reusable command sequences

Advanced Features

  • JavaScript evaluation: EVAL code
  • Variables: SET name = "value"
  • Complex selectors: CSS selectors in backticks

🎮 Interactive Playground Features

The tutorial includes a fully interactive web app with:

1. Authentication System

  • Login form with validation
  • Session management
  • Protected content

2. Dynamic Content

  • Infinite scroll products
  • Pagination controls
  • Load more buttons

3. Complex Forms

  • Multi-step wizards
  • Dynamic field visibility
  • Form validation

4. Interactive Elements

  • Tabs and accordions
  • Modals and popups
  • Expandable content

5. Data Tables

  • Sortable columns
  • Search functionality
  • Export options

🛠️ Tutorial Features

Live Code Editor

  • Syntax highlighting
  • Real-time compilation
  • Error messages with suggestions

JavaScript Output Viewer

  • See generated JavaScript code
  • Edit and test JS directly
  • Understand the compilation

Visual Execution

  • Step-by-step progress
  • Element highlighting
  • Console output

Example Scripts

Load pre-written examples demonstrating: - Cookie banner handling - Login workflows - Infinite scroll automation - Multi-step form completion - Complex interaction sequences

📖 Tutorial Sections

1. Getting Started

Learn basic commands and syntax:

GO https://example.com
WAIT `.content` 5
CLICK `.button`

2. Handling Dynamic Content

Master waiting strategies and conditionals:

IF (EXISTS `.popup`) THEN CLICK `.close`
WAIT `.results` 10

3. Form Automation

Fill and submit forms:

CLICK `#email`
TYPE "user@example.com"
CLICK `button[type="submit"]`

4. Advanced Workflows

Build complex automation flows:

PROC login
  CLICK `#username`
  TYPE $username
  CLICK `#password`
  TYPE $password
  CLICK `#login-btn`
ENDPROC

SET username = "demo"
SET password = "pass123"
login

🎯 Practice Challenges

Handle the cookie banner and newsletter popup that appear on page load.

Challenge 2: Complete Login

Successfully log into the application using the demo credentials.

Challenge 3: Load All Products

Use infinite scroll to load all 100 products in the catalog.

Challenge 4: Multi-step Survey

Complete the entire multi-step survey form.

Challenge 5: Full Workflow

Create a script that logs in, browses products, and exports data.

💡 Tips & Tricks

1. Use Specific Selectors

# Good - specific
CLICK `button.submit-order`

# Bad - too generic
CLICK `button`

2. Always Handle Popups

# Check for common popups
IF (EXISTS `.cookie-banner`) THEN CLICK `.accept`
IF (EXISTS `.newsletter-modal`) THEN CLICK `.close`

3. Add Appropriate Waits

# Wait for elements before interacting
WAIT `.form` 5
CLICK `#submit`

4. Use Procedures for Reusability

PROC handle_popups
  IF (EXISTS `.popup`) THEN CLICK `.close`
  IF (EXISTS `.cookie-banner`) THEN CLICK `.accept`
ENDPROC

# Use anywhere
handle_popups

🔧 Troubleshooting

Common Issues

  1. "Element not found"
  2. Add a WAIT before clicking
  3. Check selector specificity
  4. Verify element exists with IF

  5. "Timeout waiting for selector"

  6. Increase timeout value
  7. Check if element is dynamically loaded
  8. Verify selector is correct

  9. "Missing THEN keyword"

  10. All IF statements need THEN
  11. Format: IF (condition) THEN action

🚀 Using with Crawl4AI

Once you've mastered C4A-Script in the tutorial, use it with Crawl4AI:

from crawl4ai import AsyncWebCrawler, CrawlerRunConfig

config = CrawlerRunConfig(
    url="https://example.com",
    c4a_script="""
    WAIT `.content` 5
    IF (EXISTS `.load-more`) THEN CLICK `.load-more`
    WAIT `.new-content` 3
    """
)

async with AsyncWebCrawler() as crawler:
    result = await crawler.arun(config=config)

📝 Example Scripts

Check the scripts/ folder for complete examples: - 01-basic-interaction.c4a - Getting started - 02-login-flow.c4a - Authentication - 03-infinite-scroll.c4a - Dynamic content - 04-multi-step-form.c4a - Complex forms - 05-complex-workflow.c4a - Full automation

🏗️ Developer Guide

Project Architecture

tutorial/
├── server.py              # Flask application server
├── assets/               # Tutorial-specific assets
│   ├── app.js            # Main application logic
│   ├── c4a-blocks.js     # Custom Blockly blocks
│   ├── c4a-generator.js  # Code generation
│   ├── blockly-manager.js # Blockly integration
│   └── styles.css        # Main styling
├── playground/           # Interactive demo environment
│   ├── index.html        # Demo web application
│   ├── app.js           # Demo app logic
│   └── styles.css       # Demo styling
├── scripts/             # Example C4A scripts
└── index.html           # Main tutorial interface

Key Components

1. TutorialApp (assets/app.js)

Main application controller managing: - Code editor integration (CodeMirror) - Script execution and browser preview - Tutorial navigation and lessons - State management and persistence

2. BlocklyManager (assets/blockly-manager.js)

Visual programming interface: - Custom C4A-Script block definitions - Bidirectional sync between visual blocks and text - Real-time code generation - Dark theme integration

3. Recording System

Powers the recording functionality: - Browser event capture - Smart event grouping and filtering - Automatic C4A-Script generation - Timeline visualization

Customization

Adding New Commands

  1. Define Block (assets/c4a-blocks.js)
  2. Add Generator (assets/c4a-generator.js)
  3. Update Parser (assets/blockly-manager.js)

Themes and Styling

  • Main styles: assets/styles.css
  • Theme variables: CSS custom properties
  • Dark mode: Auto-applied based on system preference

Configuration

# server.py configuration
PORT = 8000
DEBUG = True
THREADED = True

API Endpoints

  • GET / - Main tutorial interface
  • GET /playground/ - Interactive demo environment
  • POST /execute - Script execution endpoint
  • GET /examples/<script> - Load example scripts

🔧 Troubleshooting

Common Issues

Port Already in Use

# Kill existing process
lsof -ti:8000 | xargs kill -9
# Or use different port
python server.py --port 8001

Blockly Not Loading - Check browser console for JavaScript errors - Verify all static files are served correctly - Ensure proper script loading order

Recording Issues - Verify iframe permissions - Check cross-origin communication - Ensure event listeners are attached

Debug Mode

Enable detailed logging by setting DEBUG = True in assets/app.js

📚 Additional Resources

🤝 Contributing

Bug Reports

  1. Check existing issues on GitHub
  2. Provide minimal reproduction steps
  3. Include browser and system information
  4. Add relevant console logs

Feature Requests

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/my-feature
  3. Test thoroughly with different browsers
  4. Update documentation
  5. Submit pull request

Code Style

  • Use consistent indentation (2 spaces for JS, 4 for Python)
  • Add comments for complex logic
  • Follow existing naming conventions
  • Test with multiple browsers

Happy Automating! 🎉

Need help? Check our documentation or open an issue on GitHub.


Using storage_state to Pre-Load Cookies and LocalStorage

Crawl4ai’s AsyncWebCrawler lets you preserve and reuse session data, including cookies and localStorage, across multiple runs. By providing a storage_state, you can start your crawls already “logged in” or with any other necessary session data—no need to repeat the login flow every time.

What is storage_state?

storage_state can be:

  • A dictionary containing cookies and localStorage data.
  • A path to a JSON file that holds this information.

When you pass storage_state to the crawler, it applies these cookies and localStorage entries before loading any pages. This means your crawler effectively starts in a known authenticated or pre-configured state.

Example Structure

Here’s an example storage state:

{
  "cookies": [
    {
      "name": "session",
      "value": "abcd1234",
      "domain": "example.com",
      "path": "/",
      "expires": 1675363572.037711,
      "httpOnly": false,
      "secure": false,
      "sameSite": "None"
    }
  ],
  "origins": [
    {
      "origin": "https://example.com",
      "localStorage": [
        { "name": "token", "value": "my_auth_token" },
        { "name": "refreshToken", "value": "my_refresh_token" }
      ]
    }
  ]
}

This JSON sets a session cookie and two localStorage entries (token and refreshToken) for https://example.com.


Passing storage_state as a Dictionary

You can directly provide the data as a dictionary:

import asyncio
from crawl4ai import AsyncWebCrawler

async def main():
    storage_dict = {
        "cookies": [
            {
                "name": "session",
                "value": "abcd1234",
                "domain": "example.com",
                "path": "/",
                "expires": 1675363572.037711,
                "httpOnly": False,
                "secure": False,
                "sameSite": "None"
            }
        ],
        "origins": [
            {
                "origin": "https://example.com",
                "localStorage": [
                    {"name": "token", "value": "my_auth_token"},
                    {"name": "refreshToken", "value": "my_refresh_token"}
                ]
            }
        ]
    }

    async with AsyncWebCrawler(
        headless=True,
        storage_state=storage_dict
    ) as crawler:
        result = await crawler.arun(url='https://example.com/protected')
        if result.success:
            print("Crawl succeeded with pre-loaded session data!")
            print("Page HTML length:", len(result.html))

if __name__ == "__main__":
    asyncio.run(main())

Passing storage_state as a File

If you prefer a file-based approach, save the JSON above to mystate.json and reference it:

import asyncio
from crawl4ai import AsyncWebCrawler

async def main():
    async with AsyncWebCrawler(
        headless=True,
        storage_state="mystate.json"  # Uses a JSON file instead of a dictionary
    ) as crawler:
        result = await crawler.arun(url='https://example.com/protected')
        if result.success:
            print("Crawl succeeded with pre-loaded session data!")
            print("Page HTML length:", len(result.html))

if __name__ == "__main__":
    asyncio.run(main())

Using storage_state to Avoid Repeated Logins (Sign In Once, Use Later)

A common scenario is when you need to log in to a site (entering username/password, etc.) to access protected pages. Doing so every crawl is cumbersome. Instead, you can:

  1. Perform the login once in a hook.
  2. After login completes, export the resulting storage_state to a file.
  3. On subsequent runs, provide that storage_state to skip the login step.

Step-by-Step Example:

First Run (Perform Login and Save State):

import asyncio
from crawl4ai import AsyncWebCrawler, CacheMode
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator

async def on_browser_created_hook(browser):
    # Access the default context and create a page
    context = browser.contexts[0]
    page = await context.new_page()

    # Navigate to the login page
    await page.goto("https://example.com/login", wait_until="domcontentloaded")

    # Fill in credentials and submit
    await page.fill("input[name='username']", "myuser")
    await page.fill("input[name='password']", "mypassword")
    await page.click("button[type='submit']")
    await page.wait_for_load_state("networkidle")

    # Now the site sets tokens in localStorage and cookies
    # Export this state to a file so we can reuse it
    await context.storage_state(path="my_storage_state.json")
    await page.close()

async def main():
    # First run: perform login and export the storage_state
    async with AsyncWebCrawler(
        headless=True,
        verbose=True,
        hooks={"on_browser_created": on_browser_created_hook},
        use_persistent_context=True,
        user_data_dir="./my_user_data"
    ) as crawler:

        # After on_browser_created_hook runs, we have storage_state saved to my_storage_state.json
        result = await crawler.arun(
            url='https://example.com/protected-page',
            cache_mode=CacheMode.BYPASS,
            markdown_generator=DefaultMarkdownGenerator(options={"ignore_links": True}),
        )
        print("First run result success:", result.success)
        if result.success:
            print("Protected page HTML length:", len(result.html))

if __name__ == "__main__":
    asyncio.run(main())

Second Run (Reuse Saved State, No Login Needed):

import asyncio
from crawl4ai import AsyncWebCrawler, CacheMode
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator

async def main():
    # Second run: no need to hook on_browser_created this time.
    # Just provide the previously saved storage state.
    async with AsyncWebCrawler(
        headless=True,
        verbose=True,
        use_persistent_context=True,
        user_data_dir="./my_user_data",
        storage_state="my_storage_state.json"  # Reuse previously exported state
    ) as crawler:

        # Now the crawler starts already logged in
        result = await crawler.arun(
            url='https://example.com/protected-page',
            cache_mode=CacheMode.BYPASS,
            markdown_generator=DefaultMarkdownGenerator(options={"ignore_links": True}),
        )
        print("Second run result success:", result.success)
        if result.success:
            print("Protected page HTML length:", len(result.html))

if __name__ == "__main__":
    asyncio.run(main())

What’s Happening Here?

  • During the first run, the on_browser_created_hook logs into the site.
  • After logging in, the crawler exports the current session (cookies, localStorage, etc.) to my_storage_state.json.
  • On subsequent runs, passing storage_state="my_storage_state.json" starts the browser context with these tokens already in place, skipping the login steps.

Sign Out Scenario: If the website allows you to sign out by clearing tokens or by navigating to a sign-out URL, you can also run a script that uses on_browser_created_hook or arun to simulate signing out, then export the resulting storage_state again. That would give you a baseline “logged out” state to start fresh from next time.


Conclusion

By using storage_state, you can skip repetitive actions, like logging in, and jump straight into crawling protected content. Whether you provide a file path or a dictionary, this powerful feature helps maintain state between crawls, simplifying your data extraction pipelines.


A powerful web scraping API that converts any website into structured data using AI. Features a beautiful minimalist frontend interface and support for custom LLM models!

Features

  • AI-Powered Scraping: Provide a URL and plain English query to extract structured data
  • Beautiful Frontend: Modern minimalist black-and-white interface with smooth UX
  • Custom Model Support: Use any LLM provider (OpenAI, Gemini, Anthropic, etc.) with your own API keys
  • Model Management: Save, list, and manage multiple model configurations via web interface
  • Dual Scraping Approaches: Choose between Schema-based (faster) or LLM-based (more flexible) extraction
  • API Request History: Automatic saving and display of all API requests with cURL commands
  • Schema Caching: Intelligent caching of generated schemas for faster subsequent requests
  • Duplicate Prevention: Avoids saving duplicate requests (same URL + query)
  • RESTful API: Easy-to-use HTTP endpoints for all operations

Quick Start

1. Install Dependencies

pip install -r requirements.txt

2. Start the API Server

python app.py

The server will start on http://localhost:8000 with a beautiful web interface!

3. Using the Web Interface

Once the server is running, open your browser and go to http://localhost:8000 to access the modern web interface!

Pages:

  • Scrape Data: Enter URLs and queries to extract structured data
  • Models: Manage your AI model configurations (add, list, delete)
  • API Requests: View history of all scraping requests with cURL commands

Features:

  • Minimalist Design: Clean black-and-white theme inspired by modern web apps
  • Real-time Results: See extracted data in formatted JSON
  • Copy to Clipboard: Easy copying of results
  • Toast Notifications: User-friendly feedback
  • Dual Scraping Modes: Choose between Schema-based and LLM-based approaches

Model Management

Adding Models via Web Interface

  1. Go to the Models page
  2. Enter your model details:
  3. Provider: LLM provider (e.g., gemini/gemini-2.5-flash, openai/gpt-4o)
  4. API Token: Your API key for the provider
  5. Click "Add Model"

API Usage for Model Management

Save a Model Configuration

curl -X POST "http://localhost:8000/models" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "gemini/gemini-2.5-flash",
    "api_token": "your-api-key-here"
  }'

List Saved Models

curl -X GET "http://localhost:8000/models"

Delete a Model Configuration

curl -X DELETE "http://localhost:8000/models/my-gemini"

Scraping Approaches

1. Schema-based Scraping (Faster)

  • Generates CSS selectors for targeted extraction
  • Caches schemas for repeated requests
  • Faster execution for structured websites

2. LLM-based Scraping (More Flexible)

  • Direct LLM extraction without schema generation
  • More flexible for complex or dynamic content
  • Better for unstructured data extraction

Supported LLM Providers

The API supports any LLM provider that crawl4ai supports, including:

  • Google Gemini: gemini/gemini-2.5-flash, gemini/gemini-pro
  • OpenAI: openai/gpt-4, openai/gpt-3.5-turbo
  • Anthropic: anthropic/claude-3-opus, anthropic/claude-3-sonnet
  • And more...

API Endpoints

Core Endpoints

  • POST /scrape - Schema-based scraping
  • POST /scrape-with-llm - LLM-based scraping
  • GET /schemas - List cached schemas
  • POST /clear-cache - Clear schema cache
  • GET /health - Health check

Model Management Endpoints

  • GET /models - List saved model configurations
  • POST /models - Save a new model configuration
  • DELETE /models/{model_name} - Delete a model configuration

API Request History

  • GET /saved-requests - List all saved API requests
  • DELETE /saved-requests/{request_id} - Delete a saved request

Request/Response Examples

Scrape Request

{
  "url": "https://example.com",
  "query": "Extract the product name, price, and description",
  "model_name": "my-custom-model"
}

Scrape Response

{
  "success": true,
  "url": "https://example.com",
  "query": "Extract the product name, price, and description",
  "extracted_data": {
    "product_name": "Example Product",
    "price": "$99.99",
    "description": "This is an example product description"
  },
  "schema_used": { ... },
  "timestamp": "2024-01-01T12:00:00Z"
}

Model Configuration Request

{
  "provider": "gemini/gemini-2.5-flash",
  "api_token": "your-api-key-here"
}

Testing

Run the test script to verify the model management functionality:

python test_models.py

File Structure

parse_example/
├── api_server.py          # FastAPI server with all endpoints
├── web_scraper_lib.py     # Core scraping library
├── test_models.py         # Test script for model management
├── requirements.txt       # Dependencies
├── static/               # Frontend files
│   ├── index.html        # Main HTML interface
│   ├── styles.css        # CSS styles (minimalist theme)
│   └── script.js         # JavaScript functionality
├── schemas/              # Cached schemas
├── models/               # Saved model configurations
├── saved_requests/       # API request history
└── README.md            # This file

Advanced Usage

Using the Library Directly

from web_scraper_lib import WebScraperAgent

# Initialize agent
agent = WebScraperAgent()

# Save a model configuration
agent.save_model_config(
    model_name="my-model",
    provider="openai/gpt-4",
    api_token="your-api-key"
)

# Schema-based scraping
result = await agent.scrape_data(
    url="https://example.com",
    query="Extract product information",
    model_name="my-model"
)

# LLM-based scraping
result = await agent.scrape_data_with_llm(
    url="https://example.com",
    query="Extract product information",
    model_name="my-model"
)

Schema Caching

The system automatically caches generated schemas based on URL and query combinations:

  • First request: Generates schema using AI
  • Subsequent requests: Uses cached schema for faster extraction

API Request History

All API requests are automatically saved with: - Request details (URL, query, model used) - Response data - Timestamp - cURL command for re-execution

Duplicate Prevention

The system prevents saving duplicate requests: - Same URL + query combinations are not saved multiple times - Returns existing request ID for duplicates - Keeps the API request history clean

Error Handling

The API provides detailed error messages for common issues:

  • Invalid URLs
  • Missing model configurations
  • API key errors
  • Network timeouts
  • Parsing errors

A real-world demonstration of Crawl4AI's multi-step crawling with LLM-generated automation scripts.

🎯 What This Example Shows

This example demonstrates advanced Crawl4AI features: - LLM-Generated Scripts: Automatically create C4A-Script from HTML snippets - Multi-Step Crawling: Navigate through multiple pages using session persistence - Structured Data Extraction: Extract product data using JSON CSS schemas - Visual Automation: Watch the browser perform the search (headless=False)

🚀 How It Works

1. Script Generation Phase

The example uses C4ACompiler.generate_script() to analyze Amazon's HTML and create: - Search Script: Automates filling the search box and clicking search - Extraction Schema: Defines how to extract product information

2. Crawling Workflow

Homepage → Execute Search Script → Extract Products → Save Results

All steps use the same session_id to maintain browser state.

3. Data Extraction

Products are extracted with: - Title, price, rating, reviews - Delivery information - Sponsored/Small Business badges - Direct product URLs

📁 Files

  • amazon_r2d2_search.py - Main example script
  • header.html - Amazon search bar HTML (provided)
  • product.html - Product card HTML (provided)
  • Generated files:
  • generated_search_script.c4a - Auto-generated search automation
  • generated_product_schema.json - Auto-generated extraction rules
  • extracted_products.json - Final scraped data
  • search_results_screenshot.png - Visual proof of results

🏃 Running the Example

  1. Prerequisites
# Ensure Crawl4AI is installed
pip install crawl4ai

# Set up LLM API key (for script generation)
export OPENAI_API_KEY="your-key-here"
  1. Run the scraper
python amazon_r2d2_search.py
  1. Watch the magic!
  2. Browser window opens (not headless)
  3. Navigates to Amazon.com
  4. Searches for "r2d2"
  5. Extracts all products
  6. Saves results to JSON

📊 Sample Output

[
  {
    "title": "Death Star BB8 R2D2 Golf Balls with 20 Printed tees",
    "price": "29.95",
    "rating": "4.7",
    "reviews_count": "184",
    "delivery": "FREE delivery Thu, Jun 19",
    "url": "https://www.amazon.com/Death-Star-R2D2-Balls-Printed/dp/B081XSYZMS",
    "is_sponsored": true,
    "small_business": true
  },
  ...
]

🔍 Key Features Demonstrated

Session Persistence

# Same session_id across multiple arun() calls
config = CrawlerRunConfig(
    session_id="amazon_r2d2_session",
    # ... other settings
)

LLM Script Generation

# Generate automation from natural language + HTML
script = C4ACompiler.generate_script(
    html=header_html,
    query="Find search box, type 'r2d2', click search",
    mode="c4a"
)

JSON CSS Extraction

# Structured data extraction with CSS selectors
schema = {
    "baseSelector": "[data-component-type='s-search-result']",
    "fields": [
        {"name": "title", "selector": "h2 a span", "type": "text"},
        {"name": "price", "selector": ".a-price-whole", "type": "text"}
    ]
}

🛠️ Customization

Search Different Products

Change the search term in the script generation:

search_goal = """
...
3. Type "star wars lego" into the search box
...
"""

Extract More Data

Add fields to the extraction schema:

"fields": [
    # ... existing fields
    {"name": "prime", "selector": ".s-prime", "type": "exists"},
    {"name": "image_url", "selector": "img.s-image", "type": "attribute", "attribute": "src"}
]

Use Different Sites

Adapt the approach for other e-commerce sites by: 1. Providing their HTML snippets 2. Adjusting the search goals 3. Updating the extraction schema

🎓 Learning Points

  1. No Manual Scripting: LLM generates all automation code
  2. Session Management: Maintain state across page navigations
  3. Robust Extraction: Handle dynamic content and multiple products
  4. Error Handling: Graceful fallbacks if generation fails

🐛 Troubleshooting

  • "No products found": Check if Amazon's HTML structure changed
  • "Script generation failed": Ensure LLM API key is configured
  • "Page timeout": Increase wait times in the config
  • "Session lost": Ensure same session_id is used consistently

📚 Next Steps

  • Try searching for different products
  • Add pagination to get more results
  • Extract product details pages
  • Compare prices across different sellers
  • Build a price monitoring system

This example shows the power of combining LLM intelligence with web automation. The scripts adapt to HTML changes and natural language instructions make automation accessible to everyone!


When dealing with very long web pages, traditional full-page screenshots can be slow or fail entirely. For large pages (like extensive Wikipedia articles), generating a single massive screenshot often leads to delays, memory issues, or style differences.

The New Approach: We’ve introduced a new feature that effortlessly handles even the biggest pages by first exporting them as a PDF, then converting that PDF into a high-quality image. This approach leverages the browser’s built-in PDF rendering, making it both stable and efficient for very long content. You also have the option to directly save the PDF for your own usage—no need for multiple passes or complex stitching logic.

Key Benefits: - Reliability: The PDF export never times out and works regardless of page length. - Versatility: Get both the PDF and a screenshot in one crawl, without reloading or reprocessing. - Performance: Skips manual scrolling and stitching images, reducing complexity and runtime.

Simple Example:

import os
import sys
import asyncio
from crawl4ai import AsyncWebCrawler, CacheMode, CrawlerRunConfig

# Adjust paths as needed
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(parent_dir)
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))

async def main():
    async with AsyncWebCrawler() as crawler:
        # Request both PDF and screenshot
        result = await crawler.arun(
            url='https://en.wikipedia.org/wiki/List_of_common_misconceptions',
            config=CrawlerRunConfig(
                cache_mode=CacheMode.BYPASS,
                pdf=True,
                screenshot=True
            )
        )

        if result.success:
            # Save screenshot
            if result.screenshot:
                from base64 import b64decode
                with open(os.path.join(__location__, "screenshot.png"), "wb") as f:
                    f.write(b64decode(result.screenshot))

            # Save PDF
            if result.pdf:
                with open(os.path.join(__location__, "page.pdf"), "wb") as f:
                    f.write(result.pdf)

if __name__ == "__main__":
    asyncio.run(main())

What Happens Under the Hood: - Crawl4AI navigates to the target page. - If pdf=True, it exports the current page as a full PDF, capturing all of its content no matter the length. - If screenshot=True, and a PDF is already available, it directly converts the first page of that PDF to an image for you—no repeated loading or scrolling. - Finally, you get your PDF and/or screenshot ready to use.

Controlling scroll speed for full-page screenshots: When a page is taller than screenshot_height_threshold (default ~20,000px) and no PDF is available, Crawl4AI scrolls through the page to capture a stitched full-page screenshot. Use scroll_delay to control the pause between scroll steps:

config = CrawlerRunConfig(
    screenshot=True,
    scroll_delay=0.5,  # Wait 0.5s between scroll steps (default: 0.2)
)

This is particularly useful for pages with lazy-loaded images or animations that need time to render during scrolling.


Viewport-Only Screenshots

If you only need a screenshot of the visible viewport (not the entire page), use the force_viewport_screenshot option. This is significantly faster and produces smaller images, especially for long pages.

import os
import asyncio
from base64 import b64decode
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig

async def main():
    async with AsyncWebCrawler() as crawler:
        result = await crawler.arun(
            url='https://en.wikipedia.org/wiki/List_of_common_misconceptions',
            config=CrawlerRunConfig(
                screenshot=True,
                force_viewport_screenshot=True  # Only capture the visible viewport
            )
        )

        if result.success and result.screenshot:
            with open("viewport_screenshot.png", "wb") as f:
                f.write(b64decode(result.screenshot))
            print("Viewport screenshot saved!")

if __name__ == "__main__":
    asyncio.run(main())

When to use viewport-only screenshots: - You only need what's visible above the fold - You want faster screenshot capture on long pages - You need smaller image sizes for thumbnails or previews

Conclusion: With this feature, Crawl4AI becomes even more robust and versatile for large-scale content extraction. Whether you need a PDF snapshot or a quick screenshot, you now have a reliable solution for even the most extensive webpages.


Introduction

When scraping dynamic websites, it’s common to encounter “Load More” or “Next” buttons that must be clicked to reveal new content. Crawl4AI provides a straightforward way to handle these situations using JavaScript execution and waiting conditions. In this tutorial, we’ll cover two approaches:

  1. Step-by-step (Session-based) Approach: Multiple calls to arun() to progressively load more content.
  2. Single-call Approach: Execute a more complex JavaScript snippet inside a single arun() call to handle all clicks at once before the extraction.

Prerequisites

  • A working installation of Crawl4AI
  • Basic familiarity with Python’s async/await syntax

Step-by-Step Approach

Use a session ID to maintain state across multiple arun() calls:

from crawl4ai import AsyncWebCrawler, CacheMode

js_code = [
    # This JS finds the “Next” button and clicks it
    "const nextButton = document.querySelector('button.next'); nextButton && nextButton.click();"
]

wait_for_condition = "css:.new-content-class"

async with AsyncWebCrawler(headless=True, verbose=True) as crawler:
    # 1. Load the initial page
    result_initial = await crawler.arun(
        url="https://example.com",
        cache_mode=CacheMode.BYPASS,
        session_id="my_session"
    )

    # 2. Click the 'Next' button and wait for new content
    result_next = await crawler.arun(
        url="https://example.com",
        session_id="my_session",
        js_code=js_code,
        wait_for=wait_for_condition,
        js_only=True,
        cache_mode=CacheMode.BYPASS
    )

# `result_next` now contains the updated HTML after clicking 'Next'

Key Points: - session_id: Keeps the same browser context open. - js_code: Executes JavaScript in the context of the already loaded page. - wait_for: Ensures the crawler waits until new content is fully loaded. - js_only=True: Runs the JS in the current session without reloading the page.

By repeating the arun() call multiple times and modifying the js_code (e.g., clicking different modules or pages), you can iteratively load all the desired content.

Single-call Approach

If the page allows it, you can run a single arun() call with a more elaborate JavaScript snippet that: - Iterates over all the modules or "Next" buttons - Clicks them one by one - Waits for content updates between each click - Once done, returns control to Crawl4AI for extraction.

Example snippet:

from crawl4ai import AsyncWebCrawler, CacheMode

js_code = [
    # Example JS that clicks multiple modules:
    """
    (async () => {
      const modules = document.querySelectorAll('.module-item');
      for (let i = 0; i < modules.length; i++) {
        modules[i].scrollIntoView();
        modules[i].click();
        // Wait for each module’s content to load, adjust 100ms as needed
        await new Promise(r => setTimeout(r, 100));
      }
    })();
    """
]

async with AsyncWebCrawler(headless=True, verbose=True) as crawler:
    result = await crawler.arun(
        url="https://example.com",
        js_code=js_code,
        wait_for="css:.final-loaded-content-class",
        cache_mode=CacheMode.BYPASS
    )

# `result` now contains all content after all modules have been clicked in one go.

Key Points: - All interactions (clicks and waits) happen before the extraction. - Ideal for pages where all steps can be done in a single pass.

Choosing the Right Approach

  • Step-by-Step (Session-based):
  • Good when you need fine-grained control or must dynamically check conditions before clicking the next page.
  • Useful if the page requires multiple conditions checked at runtime.

  • Single-call:

  • Perfect if the sequence of interactions is known in advance.
  • Cleaner code if the page’s structure is consistent and predictable.

Conclusion

Crawl4AI makes it easy to handle dynamic content: - Use session IDs and multiple arun() calls for stepwise crawling. - Or pack all actions into one arun() call if the interactions are well-defined upfront.

This flexibility ensures you can handle a wide range of dynamic web pages efficiently.