参考

注意:此功能与arun()但专注于并发或批量抓取。如果你不熟悉arun()使用方法,请先阅读该文档,然后查看此文档以了解差异。

函数签名

async def arun_many(
    urls: Union[List[str], List[Any]],
    config: Optional[CrawlerRunConfig] = None,
    dispatcher: Optional[BaseDispatcher] = None,
    ...
) -> Union[List[CrawlResult], AsyncGenerator[CrawlResult, None]]:
    """
    Crawl multiple URLs concurrently or in batches.

    :param urls: A list of URLs (or tasks) to crawl.
    :param config: (Optional) A default `CrawlerRunConfig` applying to each crawl.
    :param dispatcher: (Optional) A concurrency controller (e.g. MemoryAdaptiveDispatcher).
    ...
    :return: Either a list of `CrawlResult` objects, or an async generator if streaming is enabled.
    """

arun()

1.多个 URL:

  • 您无需抓取单个 URL,而是传递它们的列表(字符串或任务)。
  • 函数返回以下列表CrawlResult或者如果启用了流,则使用异步生成器。

2.并发与调度器:

  • param 允许高级并发控制。
  • 如果省略,则使用默认调度程序(如MemoryAdaptiveDispatcher) 供内部使用。
  • 调度程序处理并发、速率限制和基于内存的自适应节流(请参阅多 URL 抓取)。

3.流媒体支持:

  • 通过设置启用流stream=True在你的CrawlerRunConfig
  • 流式传输时,使用async for在结果可用时进行处理。
  • 非常适合处理大量 URL,无需等待所有 URL 完成。

4.并行执行**:

  • 可以在后台同时运行多个请求。
  • 每个CrawlResult可能还包括dispatch_result具有并发详细信息(例如内存使用情况、开始/结束时间)。

基本示例(批处理模式)

# Minimal usage: The default dispatcher will be used
results = await crawler.arun_many(
    urls=["https://site1.com", "https://site2.com"],
    config=CrawlerRunConfig(stream=False)  # Default behavior
)

for res in results:
    if res.success:
        print(res.url, "crawled OK!")
    else:
        print("Failed:", res.url, "-", res.error_message)

流示例

config = CrawlerRunConfig(
    stream=True,  # Enable streaming mode
    cache_mode=CacheMode.BYPASS
)

# Process results as they complete
async for result in await crawler.arun_many(
    urls=["https://site1.com", "https://site2.com", "https://site3.com"],
    config=config
):
    if result.success:
        print(f"Just completed: {result.url}")
        # Process each result immediately
        process_result(result)

使用自定义调度程序

dispatcher = MemoryAdaptiveDispatcher(
    memory_threshold_percent=70.0,
    max_session_permit=10
)
results = await crawler.arun_many(
    urls=["https://site1.com", "https://site2.com", "https://site3.com"],
    config=my_run_config,
    dispatcher=dispatcher
)

要点: - 每个 URL 由相同或单独的会话处理,具体取决于调度程序的策略。 -dispatch_result在每个CrawlResult(如果使用并发)可以保存内存和时间信息。 - 如果您需要处理身份验证或会话 ID,请在每个单独的任务中或运行配置中传递它们。

返回值

要么列出CrawlResult对象,或者如果启用了流,则为异步生成器。您可以迭代检查result.success或阅读每件物品的extracted_contentmarkdown , 或者dispatch_result


调度程序参考

  • :根据系统内存使用情况动态管理并发。
  • :固定并发限制,比较简单,但适应性较差。

有关高级用法或自定义设置,请参阅使用调度程序进行多 URL 抓取


常见陷阱

1. 大型列表:如果您传递数千个 URL,请注意内存或速率限制。调度程序可以提供帮助。

2. 会话重用:如果您需要专门的登录或持久上下文,请确保您的调度程序或任务相应地处理会话。

3. 错误处理:EachCrawlResult可能会因不同原因而失败——务必检查result.successerror_message然后继续。


结论

使用arun_many()当您需要同时或在受控的并行任务中抓取多个 URL 时。如果您需要高级并发功能(例如基于内存的自适应节流或复杂的速率限制),请提供调度程序。每个结果都是一个标准CrawlResult,可能还会增加并发统计数据(dispatch_result ) 进行更深入的检查。有关并发逻辑和调度程序的更多详细信息,请参阅高级多 URL 爬取文档。


> Feedback