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_code
在CrawlerRunConfig
模拟这些动作,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_for
在CrawlerRunConfig
管理下载时间。 - 错误处理:处理错误以妥善管理失败的下载或不正确的路径。
- 安全性:使用前扫描下载的文件是否存在潜在的安全威胁。
本修订指南确保与Crawl4AI
代码库使用BrowserConfig
和CrawlerRunConfig
所有与下载相关的配置。如果需要进一步调整,请告诉我!