PDF处理策略

Crawl4AI 提供了专门的策略来处理和提取 PDF 文件的内容。这些策略允许您将 PDF 处理无缝集成到您的抓取工作流程中,无论 PDF 是在线托管还是本地存储。

PDFCrawlerStrategy

概述

AsyncCrawlerStrategy专为 PDF 文档设计。此策略不会将输入 URL 解释为 HTML 网页,而是将其视为指向 PDF 文件的指针。它本身不执行深度抓取或 HTML 解析,而是为专用的 PDF 抓取策略准备 PDF 源。其主要作用是识别 PDF 源(网页 URL 或本地文件),并将其传递到处理管道,以便AsyncWebCrawler可以处理。

何时使用

使用PDFCrawlerStrategy当您需要: - 使用AsyncWebCrawler. - 处理来自两个网址的 PDF(例如,https://example.com/document.pdf )和本地文件路径(例如,file:///path/to/your/document.pdf ). - 将 PDF 内容提取集成到统一的CrawlResult对象,允许一致地处理 PDF 数据和网页数据。

关键方法及其行为

  • :初始化策略。logger :可选AsyncLogger实例(来自crawl4ai.async_logger) 用于记录目的。
  • :此方法由AsyncWebCrawlerarun过程。它需要url(应该指向 PDF)并创建一个最小AsyncCrawlResponse。 这html此响应的属性通常为空或占位符,因为实际的 PDF 内容处理被推迟到PDFContentScrapingStrategy(或类似的 PDF 感知抓取策略)。它设置response_headers表示“application/pdf”和status_code到 200。
  • :用于清理策略所使用的资源的方法。对于PDFCrawlerStrategy,这通常是最小的。
  • /async __aexit__(self, exc_type, exc_val, exc_tb) :为策略启用异步上下文管理,允许其与async with

示例用法

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 is typically used in conjunction with PDFContentScrapingStrategy
    # The scraping strategy handles the actual PDF content extraction
    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())

优点和缺点

优点: - 启用AsyncWebCrawler使用熟悉的arun调用。 - 提供用于指定 PDF 源(URL 或本地路径)的一致接口。 - 抽象源处理,允许单独的抓取策略专注于 PDF 内容解析。

缺点: - 本身不执行任何 PDF 数据提取;它严格依赖于兼容的抓取策略(例如PDFContentScrapingStrategy) 来处理 PDF。——其本身的实用性有限;其大部分价值来自于与特定于 PDF 的内容抓取策略相结合。


PDFContentScrapingStrategy

概述

ContentScrapingStrategy旨在从 PDF 文档中提取文本、元数据以及可选的图像。它旨在与爬虫策略结合使用,该策略可以为其提供 PDF 源,例如PDFCrawlerStrategy。该策略使用NaivePDFProcessorStrategy内部执行低级 PDF 解析。

何时使用

使用PDFContentScrapingStrategy当你的AsyncWebCrawler(通常配置有PDFCrawlerStrategy) 需要:- 从 PDF 文档中逐页提取文本内容。- 检索 PDF 中嵌入的标准元数据(例如,标题、作者、主题、创建日期、页数)。- (可选)提取 PDF 页面中包含的图像。这些图像可以保存到本地目录或用于进一步处理。- 生成ScrapingResult可以转换成CrawlResult,使 PDF 内容可以像 HTML 网页内容一样被访问(例如,result.markdown ,元数据result.metadata)。

关键配置属性

初始化时PDFContentScrapingStrategy,您可以使用以下属性配置其行为:-extract_images: bool = False : 如果True,该策略将尝试从 PDF 中提取图像。-save_images_locally: bool = False : 如果True(和extract_images也是True),提取的图像将保存到磁盘中image_save_dir。 如果False,图像数据可能以另一种形式提供(例如,base64,取决于底层处理器),但不会通过此策略保存为单独的文件。 -image_save_dir: str = None :指定提取图像的保存目录,如果save_images_locallyTrue。 如果None,可能会使用默认或临时目录。 -batch_size: int = 4 :定义单个批次中处理的 PDF 页面数量。处理大型 PDF 文档时,此功能有助于管理内存。-logger: AsyncLogger = None :可选AsyncLogger用于记录的实例。

关键方法及其行为

  • :使用图像处理、批处理和日志记录的配置初始化策略。它设置了一个内部NaivePDFProcessorStrategy执行实际 PDF 解析的实例。
  • :这是爬虫调用的主要同步方法(通过ascrap) 来处理 PDF。url :PDF 文件的路径或 URL(由PDFCrawlerStrategy或类似)。html :通常与以下项一起使用时为空字符串PDFCrawlerStrategy,因为内容是 PDF,而不是 HTML。它首先确保 PDF 可在本地访问(如果url是远程的)。然后,它使用其内部 PDF 处理器提取文本、元数据和图像(如果已配置)。提取的信息被编译成ScrapingResult目的:cleaned_html :包含 PDF 的 HTML 类表示,其中每页的内容通常包含在<div>包含页码信息。media :一本字典,其中media["images"]将包含有关提取图像的信息,如果extract_images曾是Truelinks :一本字典,其中links["urls"]可以包含 PDF 内容中的 URL。metadata :保存 PDF 元数据(例如标题、作者、页数)的字典。
  • :异步版本scrap。在底层,它通常运行同步scrap在单独的线程中使用方法asyncio.to_thread以避免阻塞事件循环。
  • :用于管理 PDF 文件访问的私有辅助方法。如果url如果是远程 (http/https),它会将 PDF 下载到临时本地文件并返回其路径。如果url表示本地文件(file://或直接路径),它会解析并返回本地路径。

示例用法

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())

优点和缺点

优点:- 提供从 PDF 文档中提取文本、元数据和(可选)图像的全面方法。- 可处理远程 PDF(通过 URL)和本地 PDF 文件。- 可配置的图像提取功能允许将图像保存到磁盘或访问其数据。- 与CrawlResult对象结构,使 PDF 衍生数据能够以与网络抓取数据一致的方式访问。-batch_size在处理大型或大量 PDF 页面时,参数可以帮助管理内存消耗。

缺点: - 提取质量和性能可能因 PDF 的复杂性、编码以及它是基于图像(扫描)还是基于文本而有很大差异。 - 图像提取可能占用大量资源(如果save_images_locally是真的)。——依赖于NaivePDFProcessorStrategy内部处理,与更复杂的 PDF 解析库相比,这可能在处理非常复杂的布局、加密的 PDF 或表单时存在局限性。除非执行 OCR 步骤(默认情况下,这不是此策略的一部分),否则扫描的 PDF 将不会生成文本。- 从 PDF 中提取链接可能很简单,具体取决于超链接在文档中的嵌入方式。


> Feedback