高级用法(2/3)

(Proxy, PDF, Screenshot, SSL, Headers, & Storage State)

Crawl4AI offers multiple power-user features that go beyond simple crawling. This tutorial covers:

1. Proxy Usage 2. Capturing PDFs & Screenshots 3. Handling SSL Certificates 4. Custom Headers 5. Session Persistence & Local Storage 6. Robots.txt Compliance

Prerequisites - You have a basic grasp of AsyncWebCrawler Basics - You know how to run or configure your Python environment with Playwright installed


1. Proxy Usage

If you need to route your crawl traffic through a proxy—whether for IP rotation, geo-testing, or privacy—Crawl4AI supports it via BrowserConfig.proxy_config.

import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig

async def main():
    browser_cfg = BrowserConfig(
        proxy_config={
            "server": "http://proxy.example.com:8080",
            "username": "myuser",
            "password": "mypass",
        },
        headless=True
    )
    crawler_cfg = CrawlerRunConfig(
        verbose=True
    )

    async with AsyncWebCrawler(config=browser_cfg) as crawler:
        result = await crawler.arun(
            url="https://www.whatismyip.com/",
            config=crawler_cfg
        )
        if result.success:
            print("[OK] Page fetched via proxy.")
            print("Page HTML snippet:", result.html[:200])
        else:
            print("[ERROR]", result.error_message)

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

Key Points - proxy_config expects a dict with server and optional auth credentials. - Many commercial proxies provide an HTTP/HTTPS “gateway” server that you specify in server. - If your proxy doesn’t need auth, omit username/password.


2. Capturing PDFs & Screenshots

Sometimes you need a visual record of a page or a PDF “printout.” Crawl4AI can do both in one pass:

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

async def main():
    run_config = CrawlerRunConfig(
        cache_mode=CacheMode.BYPASS,
        screenshot=True,
        pdf=True
    )

    async with AsyncWebCrawler() as crawler:
        result = await crawler.arun(
            url="https://en.wikipedia.org/wiki/List_of_common_misconceptions",
            config=run_config
        )
        if result.success:
            print(f"Screenshot data present: {result.screenshot is not None}")
            print(f"PDF data present: {result.pdf is not None}")

            if result.screenshot:
                print(f"[OK] Screenshot captured, size: {len(result.screenshot)} bytes")
                with open("wikipedia_screenshot.png", "wb") as f:
                    f.write(b64decode(result.screenshot))
            else:
                print("[WARN] Screenshot data is None.")

            if result.pdf:
                print(f"[OK] PDF captured, size: {len(result.pdf)} bytes")
                with open("wikipedia_page.pdf", "wb") as f:
                    f.write(result.pdf)
            else:
                print("[WARN] PDF data is None.")

        else:
            print("[ERROR]", result.error_message)

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

Why PDF + Screenshot? - Large or complex pages can be slow or error-prone with “traditional” full-page screenshots. - Exporting a PDF is more reliable for very long pages. Crawl4AI automatically converts the first PDF page into an image if you request both.

Relevant Parameters - pdf=True: Exports the current page as a PDF (base64-encoded in result.pdf). - screenshot=True: Creates a screenshot (base64-encoded in result.screenshot). - scroll_delay: Controls the delay (seconds) between scroll steps when taking a full-page screenshot of a tall page. Defaults to 0.2. Increase for pages with slow-loading assets. - scan_full_page or advanced hooking can further refine how the crawler captures content.


3. Handling SSL Certificates

If you need to verify or export a site’s SSL certificate—for compliance, debugging, or data analysis—Crawl4AI can fetch it during the crawl:

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

async def main():
    tmp_dir = os.path.join(os.getcwd(), "tmp")
    os.makedirs(tmp_dir, exist_ok=True)

    config = CrawlerRunConfig(
        fetch_ssl_certificate=True,
        cache_mode=CacheMode.BYPASS
    )

    async with AsyncWebCrawler() as crawler:
        result = await crawler.arun(url="https://example.com", config=config)

        if result.success and result.ssl_certificate:
            cert = result.ssl_certificate
            print("\nCertificate Information:")
            print(f"Issuer (CN): {cert.issuer.get('CN', '')}")
            print(f"Valid until: {cert.valid_until}")
            print(f"Fingerprint: {cert.fingerprint}")

            # Export in multiple formats:
            cert.to_json(os.path.join(tmp_dir, "certificate.json"))
            cert.to_pem(os.path.join(tmp_dir, "certificate.pem"))
            cert.to_der(os.path.join(tmp_dir, "certificate.der"))

            print("\nCertificate exported to JSON/PEM/DER in 'tmp' folder.")
        else:
            print("[ERROR] No certificate or crawl failed.")

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

Key Points - fetch_ssl_certificate=True triggers certificate retrieval. - result.ssl_certificate includes methods (to_json, to_pem, to_der) for saving in various formats (handy for server config, Java keystores, etc.).


4. Custom Headers

Sometimes you need to set custom headers (e.g., language preferences, authentication tokens, or specialized user-agent strings). You can do this in multiple ways:

import asyncio
from crawl4ai import AsyncWebCrawler

async def main():
    # Option 1: Set headers at the crawler strategy level
    crawler1 = AsyncWebCrawler(
        # The underlying strategy can accept headers in its constructor
        crawler_strategy=None  # We'll override below for clarity
    )
    crawler1.crawler_strategy.update_user_agent("MyCustomUA/1.0")
    crawler1.crawler_strategy.set_custom_headers({
        "Accept-Language": "fr-FR,fr;q=0.9"
    })
    result1 = await crawler1.arun("https://www.example.com")
    print("Example 1 result success:", result1.success)

    # Option 2: Pass headers directly to `arun()`
    crawler2 = AsyncWebCrawler()
    result2 = await crawler2.arun(
        url="https://www.example.com",
        headers={"Accept-Language": "es-ES,es;q=0.9"}
    )
    print("Example 2 result success:", result2.success)

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

Notes - Some sites may react differently to certain headers (e.g., Accept-Language). - If you need advanced user-agent randomization or client hints, see Identity-Based Crawling (Anti-Bot) or use UserAgentGenerator.


5. Session Persistence & Local Storage

Crawl4AI can preserve cookies and localStorage so you can continue where you left off—ideal for logging into sites or skipping repeated auth flows.

5.1 storage_state

import asyncio
from crawl4ai import AsyncWebCrawler

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

    # Provide the storage state as a dictionary to start "already logged in"
    async with AsyncWebCrawler(
        headless=True,
        storage_state=storage_dict
    ) as crawler:
        result = await crawler.arun("https://example.com/protected")
        if result.success:
            print("Protected page content length:", len(result.html))
        else:
            print("Failed to crawl protected page")

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

5.2 Exporting & Reusing State

You can sign in once, export the browser context, and reuse it later—without re-entering credentials.

  • await context.storage_state(path="my_storage.json"): Exports cookies, localStorage, etc. to a file.
  • Provide storage_state="my_storage.json" on subsequent runs to skip the login step.

See: Detailed session management tutorial or Explanations → Browser Context & Managed Browser for more advanced scenarios (like multi-step logins, or capturing after interactive pages).


6. Robots.txt Compliance

Crawl4AI supports respecting robots.txt rules with efficient caching:

import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig

async def main():
    # Enable robots.txt checking in config
    config = CrawlerRunConfig(
        check_robots_txt=True  # Will check and respect robots.txt rules
    )

    async with AsyncWebCrawler() as crawler:
        result = await crawler.arun(
            "https://example.com",
            config=config
        )

        if not result.success and result.status_code == 403:
            print("Access denied by robots.txt")

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

Key Points - Robots.txt files are cached locally for efficiency - Cache is stored in ~/.crawl4ai/robots/robots_cache.db - Cache has a default TTL of 7 days - If robots.txt can't be fetched, crawling is allowed - Returns 403 status code if URL is disallowed


Putting It All Together

Here’s a snippet that combines multiple “advanced” features (proxy, PDF, screenshot, SSL, custom headers, and session reuse) into one run. Normally, you’d tailor each setting to your project’s needs.

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

async def main():
    # 1. Browser config with proxy + headless
    browser_cfg = BrowserConfig(
        proxy_config={
            "server": "http://proxy.example.com:8080",
            "username": "myuser",
            "password": "mypass",
        },
        headless=True,
    )

    # 2. Crawler config with PDF, screenshot, SSL, custom headers, and ignoring caches
    crawler_cfg = CrawlerRunConfig(
        pdf=True,
        screenshot=True,
        fetch_ssl_certificate=True,
        cache_mode=CacheMode.BYPASS,
        headers={"Accept-Language": "en-US,en;q=0.8"},
        storage_state="my_storage.json",  # Reuse session from a previous sign-in
        verbose=True,
    )

    # 3. Crawl
    async with AsyncWebCrawler(config=browser_cfg) as crawler:
        result = await crawler.arun(
            url = "https://secure.example.com/protected",
            config=crawler_cfg
        )

        if result.success:
            print("[OK] Crawled the secure page. Links found:", len(result.links.get("internal", [])))

            # Save PDF & screenshot
            if result.pdf:
                with open("result.pdf", "wb") as f:
                    f.write(b64decode(result.pdf))
            if result.screenshot:
                with open("result.png", "wb") as f:
                    f.write(b64decode(result.screenshot))

            # Check SSL cert
            if result.ssl_certificate:
                print("SSL Issuer CN:", result.ssl_certificate.issuer.get("CN", ""))
        else:
            print("[ERROR]", result.error_message)

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


7. Anti-Bot Features (Stealth Mode & Undetected Browser)

Crawl4AI provides two powerful features to bypass bot detection:

7.1 Stealth Mode

Stealth mode uses playwright-stealth to modify browser fingerprints and behaviors. Enable it with a simple flag:

browser_config = BrowserConfig(
    enable_stealth=True,  # Activates stealth mode
    headless=False
)

When to use: Sites with basic bot detection (checking navigator.webdriver, plugins, etc.)

7.2 Undetected Browser

For advanced bot detection, use the undetected browser adapter:

from crawl4ai import UndetectedAdapter
from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy

# Create undetected adapter
adapter = UndetectedAdapter()
strategy = AsyncPlaywrightCrawlerStrategy(
    browser_config=browser_config,
    browser_adapter=adapter
)

async with AsyncWebCrawler(crawler_strategy=strategy, config=browser_config) as crawler:
    # Your crawling code

When to use: Sites with sophisticated bot detection (Cloudflare, DataDome, etc.)

7.3 Combining Both

For maximum evasion, combine stealth mode with undetected browser:

browser_config = BrowserConfig(
    enable_stealth=True,  # Enable stealth
    headless=False
)

adapter = UndetectedAdapter()  # Use undetected browser

Choosing the Right Approach

Detection Level Recommended Approach
No protection Regular browser
Basic checks Regular + Stealth mode
Advanced protection Undetected browser
Maximum evasion Undetected + Stealth mode

Best Practice: Start with regular browser + stealth mode. Only use undetected browser if needed, as it may be slightly slower.

See Undetected Browser Mode for detailed examples.


Conclusion & Next Steps

You've now explored several advanced features:

  • Proxy Usage
  • PDF & Screenshot capturing for large or critical pages
  • SSL Certificate retrieval & exporting
  • Custom Headers for language or specialized requests
  • Session Persistence via storage state
  • Robots.txt Compliance
  • Anti-Bot Features (Stealth Mode & Undetected Browser)

With these power tools, you can build robust scraping workflows that mimic real user behavior, handle secure sites, capture detailed snapshots, manage sessions across multiple runs, and bypass bot detection—streamlining your entire data collection pipeline.

Note: In future versions, we may enable stealth mode and undetected browser by default. For now, users should explicitly enable these features when needed.

Last Updated: 2025-01-17


Crawl4AI provides specialized strategies for handling and extracting content from PDF files. These strategies allow you to seamlessly integrate PDF processing into your crawling workflows, whether the PDFs are hosted online or stored locally.

PDFCrawlerStrategy

Overview

PDFCrawlerStrategy is an implementation of AsyncCrawlerStrategy designed specifically for PDF documents. Instead of interpreting the input URL as an HTML webpage, this strategy treats it as a pointer to a PDF file. It doesn't perform deep crawling or HTML parsing itself but rather prepares the PDF source for a dedicated PDF scraping strategy. Its primary role is to identify the PDF source (web URL or local file) and pass it along the processing pipeline in a way that AsyncWebCrawler can handle.

Must be paired with PDFContentScrapingStrategy. PDFCrawlerStrategy fetches and parses nothing on its own — it returns a placeholder response and lets the scraping strategy do the download and extraction. Always set CrawlerRunConfig(scraping_strategy=PDFContentScrapingStrategy()). With any other scraping strategy the crawl still reports success=True, but the result contains only the placeholder text instead of your PDF content.

When to Use

Use PDFCrawlerStrategy when you need to: - Process PDF files using the AsyncWebCrawler. - Handle PDFs from both web URLs (e.g., https://example.com/document.pdf) and local file paths (e.g., file:///path/to/your/document.pdf). - Integrate PDF content extraction into a unified CrawlResult object, allowing consistent handling of PDF data alongside web page data.

Key Methods and Their Behavior

  • __init__(self, logger: AsyncLogger = None):
    • Initializes the strategy.
    • logger: An optional AsyncLogger instance (from crawl4ai.async_logger) for logging purposes.
  • async crawl(self, url: str, **kwargs) -> AsyncCrawlResponse:
    • This method is called by the AsyncWebCrawler during the arun process.
    • It takes the url (which should point to a PDF) and creates a minimal AsyncCrawlResponse.
    • The html attribute of this response is a short placeholder string, as the actual PDF content processing is deferred to the PDFContentScrapingStrategy (or a similar PDF-aware scraping strategy).
    • It sets response_headers to indicate "application/pdf" and status_code to 200.
    • It also sets placeholder_html=True on the response. This tells AsyncWebCrawler that the html is a stand-in, so the anti-bot content heuristics skip it — otherwise the short placeholder would be misread as a blocked, near-empty page and the crawl would be marked failed. Any custom crawler strategy that defers content extraction to its scraping strategy should set the same flag.
  • async close(self):
    • A method for cleaning up any resources used by the strategy. For PDFCrawlerStrategy, this is usually minimal.
  • async __aenter__(self) / async __aexit__(self, exc_type, exc_val, exc_tb):
    • Enables asynchronous context management for the strategy, allowing it to be used with async with.

Example Usage

import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
from crawl4ai.processors.pdf import PDFCrawlerStrategy, PDFContentScrapingStrategy

async def main():
    # Initialize the PDF crawler strategy
    pdf_crawler_strategy = PDFCrawlerStrategy()

    # PDFCrawlerStrategy must be paired with PDFContentScrapingStrategy —
    # the scraping strategy is what actually downloads and extracts the PDF
    pdf_scraping_strategy = PDFContentScrapingStrategy()
    run_config = CrawlerRunConfig(scraping_strategy=pdf_scraping_strategy)

    async with AsyncWebCrawler(crawler_strategy=pdf_crawler_strategy) as crawler:
        # Example with a remote PDF URL
        pdf_url = "https://arxiv.org/pdf/2310.06825.pdf" # A public PDF from arXiv

        print(f"Attempting to process PDF: {pdf_url}")
        result = await crawler.arun(url=pdf_url, config=run_config)

        if result.success:
            print(f"Successfully processed PDF: {result.url}")
            print(f"Metadata Title: {result.metadata.get('title', 'N/A')}")
            # Further processing of result.markdown, result.media, etc.
            # would be done here, based on what PDFContentScrapingStrategy extracts.
            if result.markdown and hasattr(result.markdown, 'raw_markdown'):
                print(f"Extracted text (first 200 chars): {result.markdown.raw_markdown[:200]}...")
            else:
                print("No markdown (text) content extracted.")
        else:
            print(f"Failed to process PDF: {result.error_message}")

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

Pros and Cons

Pros: - Enables AsyncWebCrawler to handle PDF sources directly using familiar arun calls. - Provides a consistent interface for specifying PDF sources (URLs or local paths). - Abstracts the source handling, allowing a separate scraping strategy to focus on PDF content parsing.

Cons: - Does not perform any PDF data extraction itself; it strictly relies on a compatible scraping strategy (like PDFContentScrapingStrategy) to process the PDF. - Has limited utility on its own; most of its value comes from being paired with a PDF-specific content scraping strategy.


PDFContentScrapingStrategy

Overview

PDFContentScrapingStrategy is an implementation of ContentScrapingStrategy designed to extract text, metadata, and optionally images from PDF documents. It is intended to be used in conjunction with a crawler strategy that can provide it with a PDF source, such as PDFCrawlerStrategy. This strategy uses the NaivePDFProcessorStrategy internally to perform the low-level PDF parsing.

When to Use

Use PDFContentScrapingStrategy when your AsyncWebCrawler (often configured with PDFCrawlerStrategy) needs to: - Extract textual content page by page from a PDF document. - Retrieve standard metadata embedded within the PDF (e.g., title, author, subject, creation date, page count). - Optionally, extract images contained within the PDF pages. These images can be saved to a local directory or made available for further processing. - Produce a ScrapingResult that can be converted into a CrawlResult, making PDF content accessible in a manner similar to HTML web content (e.g., text in result.markdown, metadata in result.metadata).

Key Configuration Attributes

When initializing PDFContentScrapingStrategy, you can configure its behavior using the following attributes: - extract_images: bool = False: If True, the strategy will attempt to extract images from the PDF. - save_images_locally: bool = False: If True (and extract_images is also True), extracted images will be saved to disk in the image_save_dir. If False, image data might be available in another form (e.g., base64, depending on the underlying processor) but not saved as separate files by this strategy. - image_save_dir: str = None: Specifies the directory where extracted images should be saved if save_images_locally is True. If None, a default or temporary directory might be used. - batch_size: int = 4: Defines how many PDF pages are processed in a single batch. This can be useful for managing memory when dealing with very large PDF documents. - logger: AsyncLogger = None: An optional AsyncLogger instance for logging.

Key Methods and Their Behavior

  • __init__(self, save_images_locally: bool = False, extract_images: bool = False, image_save_dir: str = None, batch_size: int = 4, logger: AsyncLogger = None):
    • Initializes the strategy with configurations for image handling, batch processing, and logging. It sets up an internal NaivePDFProcessorStrategy instance which performs the actual PDF parsing.
  • scrap(self, url: str, html: str, **params) -> ScrapingResult:
    • This is the primary synchronous method called by the crawler (via ascrap) to process the PDF.
    • url: The path or URL to the PDF file (provided by PDFCrawlerStrategy or similar).
    • html: Typically an empty string when used with PDFCrawlerStrategy, as the content is a PDF, not HTML.
    • It first ensures the PDF is accessible locally (downloads it to a temporary file if url is remote).
    • It then uses its internal PDF processor to extract text, metadata, and images (if configured).
    • The extracted information is compiled into a ScrapingResult object:
      • cleaned_html: Contains an HTML-like representation of the PDF, where each page's content is often wrapped in a <div> with page number information.
      • media: A dictionary where media["images"] will contain information about extracted images if extract_images was True.
      • links: A dictionary where links["urls"] can contain URLs found within the PDF content.
      • metadata: A dictionary holding PDF metadata (e.g., title, author, num_pages).
  • async ascrap(self, url: str, html: str, **kwargs) -> ScrapingResult:
    • The asynchronous version of scrap. Under the hood, it typically runs the synchronous scrap method in a separate thread using asyncio.to_thread to avoid blocking the event loop.
  • _get_pdf_path(self, url: str) -> str:
    • A private helper method to manage PDF file access. If the url is remote (http/https), it downloads the PDF to a temporary local file and returns its path. If url indicates a local file (file:// or a direct path), it resolves and returns the local path.

Example Usage

import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
from crawl4ai.processors.pdf import PDFCrawlerStrategy, PDFContentScrapingStrategy
import os # For creating image directory

async def main():
    # Define the directory for saving extracted images
    image_output_dir = "./my_pdf_images"
    os.makedirs(image_output_dir, exist_ok=True)

    # Configure the PDF content scraping strategy
    # Enable image extraction and specify where to save them
    pdf_scraping_cfg = PDFContentScrapingStrategy(
        extract_images=True,
        save_images_locally=True,
        image_save_dir=image_output_dir,
        batch_size=2 # Process 2 pages at a time for demonstration
    )

    # The PDFCrawlerStrategy is needed to tell AsyncWebCrawler how to "crawl" a PDF
    pdf_crawler_cfg = PDFCrawlerStrategy()

    # Configure the overall crawl run
    run_cfg = CrawlerRunConfig(
        scraping_strategy=pdf_scraping_cfg # Use our PDF scraping strategy
    )

    # Initialize the crawler with the PDF-specific crawler strategy
    async with AsyncWebCrawler(crawler_strategy=pdf_crawler_cfg) as crawler:
        pdf_url = "https://arxiv.org/pdf/2310.06825.pdf" # Example PDF

        print(f"Starting PDF processing for: {pdf_url}")
        result = await crawler.arun(url=pdf_url, config=run_cfg)

        if result.success:
            print("\n--- PDF Processing Successful ---")
            print(f"Processed URL: {result.url}")

            print("\n--- Metadata ---")
            for key, value in result.metadata.items():
                print(f"  {key.replace('_', ' ').title()}: {value}")

            if result.markdown and hasattr(result.markdown, 'raw_markdown'):
                print(f"\n--- Extracted Text (Markdown Snippet) ---")
                print(result.markdown.raw_markdown[:500].strip() + "...")
            else:
                print("\nNo text (markdown) content extracted.")

            if result.media and result.media.get("images"):
                print(f"\n--- Image Extraction ---")
                print(f"Extracted {len(result.media['images'])} image(s).")
                for i, img_info in enumerate(result.media["images"][:2]): # Show info for first 2 images
                    print(f"  Image {i+1}:")
                    print(f"    Page: {img_info.get('page')}")
                    print(f"    Format: {img_info.get('format', 'N/A')}")
                    if img_info.get('path'):
                        print(f"    Saved at: {img_info.get('path')}")
            else:
                print("\nNo images were extracted (or extract_images was False).")
        else:
            print(f"\n--- PDF Processing Failed ---")
            print(f"Error: {result.error_message}")

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

Pros and Cons

Pros: - Provides a comprehensive way to extract text, metadata, and (optionally) images from PDF documents. - Handles both remote PDFs (via URL) and local PDF files. - Configurable image extraction allows saving images to disk or accessing their data. - Integrates smoothly with the CrawlResult object structure, making PDF-derived data accessible in a way consistent with web-scraped data. - The batch_size parameter can help in managing memory consumption when processing large or numerous PDF pages.

Cons: - Extraction quality and performance can vary significantly depending on the PDF's complexity, encoding, and whether it's image-based (scanned) or text-based. - Image extraction can be resource-intensive (both CPU and disk space if save_images_locally is true). - Relies on NaivePDFProcessorStrategy internally, which might have limitations with very complex layouts, encrypted PDFs, or forms compared to more sophisticated PDF parsing libraries. Scanned PDFs will not yield text unless an OCR step is performed (which is not part of this strategy by default). - Link extraction from PDFs can be basic and depends on how hyperlinks are embedded in the document.