Crawl4AI 中的下载处理

本指南介绍如何使用 Crawl4AI 在抓取过程中处理文件下载。您将学习如何触发下载、指定下载位置以及访问已下载的文件。

启用下载

要启用下载,请设置accept_downloads参数BrowserConfig对象并将其传递给爬虫。

from crawl4ai.async_configs import BrowserConfig, AsyncWebCrawler

async def main():
    config = BrowserConfig(accept_downloads=True)  # Enable downloads globally
    async with AsyncWebCrawler(config=config) as crawler:
        # ... your crawling logic ...

asyncio.run(main())

指定下载位置

使用指定下载目录downloads_path属性BrowserConfig对象。如果没有提供,Crawl4AI 默认在.crawl4ai文件夹位于您的主目录中。

from crawl4ai.async_configs import BrowserConfig
import os

downloads_path = os.path.join(os.getcwd(), "my_downloads")  # Custom download path
os.makedirs(downloads_path, exist_ok=True)

config = BrowserConfig(accept_downloads=True, downloads_path=downloads_path)

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

触发下载

下载通常由网页上的用户交互触发,例如点击下载按钮。使用js_codeCrawlerRunConfig模拟这些动作,wait_for留出足够的时间开始下载。

from crawl4ai.async_configs import CrawlerRunConfig

config = CrawlerRunConfig(
    js_code="""
        const downloadLink = document.querySelector('a[href$=".exe"]');
        if (downloadLink) {
            downloadLink.click();
        }
    """,
    wait_for=5  # Wait 5 seconds for the download to start
)

result = await crawler.arun(url="https://www.python.org/downloads/", config=config)

访问已下载的文件

downloaded_files的属性CrawlResult对象包含下载文件的路径。

if result.downloaded_files:
    print("Downloaded files:")
    for file_path in result.downloaded_files:
        print(f"- {file_path}")
        file_size = os.path.getsize(file_path)
        print(f"- File size: {file_size} bytes")
else:
    print("No files downloaded.")

示例:下载多个文件

from crawl4ai.async_configs import BrowserConfig, CrawlerRunConfig
import os
from pathlib import Path

async def download_multiple_files(url: str, download_path: str):
    config = BrowserConfig(accept_downloads=True, downloads_path=download_path)
    async with AsyncWebCrawler(config=config) as crawler:
        run_config = CrawlerRunConfig(
            js_code="""
                const downloadLinks = document.querySelectorAll('a[download]');
                for (const link of downloadLinks) {
                    link.click();
                    // Delay between clicks
                    await new Promise(r => setTimeout(r, 2000));  
                }
            """,
            wait_for=10  # Wait for all downloads to start
        )
        result = await crawler.arun(url=url, config=run_config)

        if result.downloaded_files:
            print("Downloaded files:")
            for file in result.downloaded_files:
                print(f"- {file}")
        else:
            print("No files downloaded.")

# Usage
download_path = os.path.join(Path.home(), ".crawl4ai", "downloads")
os.makedirs(download_path, exist_ok=True)

asyncio.run(download_multiple_files("https://www.python.org/downloads/windows/", download_path))

重要注意事项

  • 浏览器上下文:下载在浏览器上下文中进行管理。确保js_code正确定位网页上的下载触发器。
  • 时机:使用wait_forCrawlerRunConfig管理下载时间。
  • 错误处理:处理错误以妥善管理失败的下载或不正确的路径。
  • 安全性:使用前扫描下载的文件是否存在潜在的安全威胁。

本修订指南确保与Crawl4AI代码库使用BrowserConfigCrawlerRunConfig所有与下载相关的配置。如果需要进一步调整,请告诉我!


> Feedback