首页
/ Crawl4AI 基于身份的爬虫实战:持久化浏览器配置、BrowserProfiler 与区域地理信息定制

Crawl4AI 基于身份的爬虫实战:持久化浏览器配置、BrowserProfiler 与区域地理信息定制

2026-09-04 23:45:00作者:尤峻淳Whitney

本文聚焦 Crawl4AI 的 Identity-Based Crawling(基于身份的爬虫)能力:通过持久化浏览器配置(Managed Browsers)复用真实的登录态、Cookie 与浏览器指纹,让你以“本人身份”访问需要登录或个性化配置的站点;同时讲解 Magic Mode 轻量自动化的定位与差异,以及 locale / timezone_id / geolocation 三项身份维度配置。读完后,你可以掌握三种创建持久化配置目录的方法、BrowserProfiler 的完整 API,以及如何组装一个带身份与地理信息的一致化爬取流程。官方教程原文见 identity-based-crawling.md

1. 两种方案总览:Managed Browsers 与 Magic Mode

Crawl4AI 提供两条让爬虫“看起来像真人”的路径,二者定位完全不同:

  • Managed Browsers(托管浏览器,推荐):创建并复用持久化浏览器配置(persistent profile)。配置目录中保存 localStorage、Cookie 和各类会话数据,爬虫运行时可以以“真实用户”的身份浏览——带上你的登录态、偏好与 Cookie。
  • Magic Mode(魔法模式):一种简化版自动化。不保存任何长期数据,仅在本次运行中模拟类人浏览行为,适合作为快速原型或临时任务的兜底方案。

Managed Browsers 的核心收益:

  • 真实的浏览体验:会话数据与浏览器指纹得以保留,站点将其视为普通用户;
  • 一次配置,重复使用:在指定的数据目录中完成一次登录或验证码之后,后续爬取无需重复这些步骤;
  • 数据可达性:只要你在自己的浏览器中能看到这些数据,就可以用自己的真实身份自动化地获取它们。

2. 创建 User Data 目录的三种方式

身份爬取的第一步,是拥有一个包含登录态的 user-data 目录。Crawl4AI 提供三种创建途径,可按需选择。

2.1 命令行方式:直接用 Playwright 的 Chromium 二进制

安装了 Crawl4AI 之后,系统内已存在 Playwright 管理的 Chromium。可以从命令行手动启动它并指定自定义数据目录:

  1. 定位 Chromium 二进制:大多数系统上,Playwright 安装的浏览器位于 ~/.cache/ms-playwright/ 或类似路径。可运行以下命令查看概览:

    python -m playwright install --dry-run
    # 或
    playwright install --dry-run
    

    例如在 Linux 上你会看到类似这样的路径:

    ~/.cache/ms-playwright/chromium-1234/chrome-linux/chrome
    
  2. --user-data-dir 启动

    # Linux 示例
    ~/.cache/ms-playwright/chromium-1234/chrome-linux/chrome \
        --user-data-dir=/home/<you>/my_chrome_profile
    
    # macOS 示例(Playwright 内置二进制)
    ~/Library/Caches/ms-playwright/chromium-1234/chrome-mac/Chromium.app/Contents/MacOS/Chromium \
        --user-data-dir=/Users/<you>/my_chrome_profile
    
    # Windows 示例(PowerShell/cmd)
    "C:\Users\<you>\AppData\Local\ms-playwright\chromium-1234\chrome-win\chrome.exe" ^
        --user-data-dir="C:\Users\<you>\my_chrome_profile"
    

    路径请以你本机 ms-playwright 缓存结构中的实际子目录为准。浏览器打开后,登录各站点、完成所需配置,然后关闭——配置数据即保存在该文件夹中。

  3. 将该目录交给 BrowserConfig.user_data_dir

    from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig
    
    browser_config = BrowserConfig(
        headless=True,
        use_managed_browser=True,
        user_data_dir="/home/<you>/my_chrome_profile",
        browser_type="chromium"
    )
    

    再次运行代码时,Crawl4AI 会复用该目录,保留会话数据、Cookie、localStorage 等。

从源码看,这条路径最终与 Crawl4AI 内部机制是同一套参数:browser_manager.pyManagedBrowser._get_browser_args() 启动 Chromium 时正是拼接 --remote-debugging-port=<port>--user-data-dir=<dir>,无头模式追加 --headless=new。也就是说,命令行手动启动与框架托管启动在参数层面完全一致,你手工登录产生的数据可被框架无缝接管。

2.2 使用 Crawl4AI CLI(最省心)

如果偏好交互式引导,可以直接使用内置 CLI 的 profile 管理命令:

  1. 启动 profile 管理器:

    crwl profiles
    
  2. 选择 "Create new profile",输入 profile 名称。此时会打开一个 Chromium 窗口,供你登录站点、设置偏好;完成后回到终端按 q 保存 profile。

  3. Profile 保存在 ~/.crawl4ai/profiles/<profile_name>(例如 /home/<you>/.crawl4ai/profiles/test_profile_1),目录内会额外生成一份 storage_state.json,用于持久化 Cookie 与会话数据。

  4. 可选择 "List profiles" 查看已有 profile 及其路径。

  5. 将保存的路径交给 BrowserConfig.user_data_dir

    from crawl4ai import AsyncWebCrawler, BrowserConfig
    
    profile_path = "/home/<you>/.crawl4ai/profiles/test_profile_1"
    
    browser_config = BrowserConfig(
        headless=True,
        use_managed_browser=True,
        user_data_dir=profile_path,
        browser_type="chromium",
    )
    
    async with AsyncWebCrawler(config=browser_config) as crawler:
        result = await crawler.arun(url="https://example.com/private")
    

CLI 还支持列出、删除 profile,甚至直接从菜单中选取 profile 试爬一个 URL。对应实现位于 cli.pymanage_profiles() 菜单、display_profiles_table() 列表展示、create_profile_interactive() 交互式创建和 delete_profile_interactive() 删除流程,全部委托给 BrowserProfiler 执行。

2.3 使用 BrowserProfiler 类(程序化)

程序化场景下,直接调用 BrowserProfiler 即可(详见第 4 节)。三种方式的本质相同:产出一个带登录态的 user_data_dir,之后交给 BrowserConfig 复用。

3. 在 Crawl4AI 中使用 Managed Browsers

拿到带会话数据的目录后,将其传入 BrowserConfig 即可。完整示例:

import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig

async def main():
    # 1) 引用你的持久化数据目录
    browser_config = BrowserConfig(
        headless=True,             # 'True' for automated runs
        verbose=True,
        use_managed_browser=True,  # Enables persistent browser strategy
        browser_type="chromium",
        user_data_dir="/path/to/my-chrome-profile"
    )

    # 2) 标准爬取配置
    crawl_config = CrawlerRunConfig(
        wait_for="css:.logged-in-content"
    )

    async with AsyncWebCrawler(config=browser_config) as crawler:
        result = await crawler.arun(url="https://example.com/private", config=crawl_config)
        if result.success:
            print("Successfully accessed private data with your identity!")
        else:
            print("Error:", result.error_message)

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

3.1 标准工作流

  1. 外部登录:通过 CLI 或 --user-data-dir=... 启动的普通浏览器完成登录;
  2. 关闭该浏览器;
  3. 在 Crawl4AI 中将同一目录传给 user_data_dir=
  4. 执行爬取:站点看到的身份与刚才登录的用户完全一致。

3.2 参数语义(源码级说明)

BrowserConfig 中与身份爬取直接相关的参数定义于 async_configs.py

  • use_managed_browser(默认 False):启用托管浏览器策略,即由 ManagedBrowser 启动一个独立进程并通过 CDP 接管,这是启用持久化配置的前提;
  • user_data_dir(默认 None):持久化会话的数据目录。从源码结构看,若不提供该参数,ManagedBrowser.start() 会调用 tempfile.mkdtemp(prefix="browser-profile-") 创建临时目录,并在 cleanup() 时删除——这意味着不给 user_data_dir 的每次运行都是“无记忆”的
  • use_persistent_context(默认 False):设置后会自动置位 use_managed_browser=True
  • channel / chrome_channel(默认 "chromium"):可选 "chrome"msedge" 等渠道,list_profiles() 的 profile 类型识别逻辑与 browser_type 一致,支持 chromium / firefox。

另外注意一个源码细节:ManagedBrowser.start() 在启动前会做一次“预清理”——终止占用同一调试端口/profile 的旧 Chromium 实例,并删除 profile 目录下的 SingletonLockSingletonSocketSingletonCookie 文件,避免 Chromium 以“Opening in existing browser session”拒绝启动。这解释了为何同一 profile 不能在两个地方同时打开,也说明 Crawl4AI 对“profile 被占用”这一常见坑做了自动处理。

4. BrowserProfiler:Profile 全生命周期管理

Crawl4AI 提供专门的 BrowserProfiler 类(browser_profiler.py)来管理浏览器 profile,支持创建、列出、删除与获取路径,默认存储目录为 ~/.crawl4ai/profiles/

4.1 创建与管理 Profile

import asyncio
from crawl4ai import BrowserProfiler

async def manage_profiles():
    # 创建 profiler 实例
    profiler = BrowserProfiler()

    # 交互式创建 profile - 会打开一个浏览器窗口
    profile_path = await profiler.create_profile(
        profile_name="my-login-profile"  # 可选:为 profile 命名
    )

    print(f"Profile saved at: {profile_path}")

    # 列出所有可用 profile
    profiles = profiler.list_profiles()

    for profile in profiles:
        print(f"Profile: {profile['name']}")
        print(f"  Path: {profile['path']}")
        print(f"  Created: {profile['created']}")
        print(f"  Browser type: {profile['type']}")

    # 按名称获取某个 profile 的完整路径
    specific_profile = profiler.get_profile_path("my-login-profile")

    # 不再需要时删除 profile
    success = profiler.delete_profile("old-profile-name")

asyncio.run(manage_profiles())

create_profile 的工作流程

  1. 打开一个浏览器窗口供你操作;
  2. 登录网站、设置偏好等;
  3. 完成后在终端按 q 关闭浏览器;
  4. Profile 保存到 Crawl4AI 的 profiles 目录,可直接用于 BrowserConfig.user_data_dir

从源码看,create_profile() 有两个值得了解的设计决策:

  • 可移植性参数:创建 profile 时会自动附加 --password-store=basic(Linux 下使用 basic 存储而非 gnome-keyring)与 --use-mock-keychain(macOS 下使用 mock keychain)。源码注释明确说明:Chrome 默认会用操作系统密钥环加密 Cookie,导致 profile 无法在机器间迁移;这两个参数保证 profile 可以从本地复制到云端服务器复用。
  • storage_state.json 落盘时机:用户按 q(或浏览器进程退出)之后、关闭浏览器之前,BrowserProfiler 会通过 Playwright 的 context.storage_state(path=...) 将 Cookie 与会话序列化为 profile 目录下的 storage_state.json——这是 Playwright 的便携 Cookie 格式(未加密),也是 profile 跨机器可用的关键。

此外 create_profile 接受 shrink_level 参数,可在创建完成后按档位压缩 profile(见 4.2)。跨平台的 q 键监听在 Windows 下使用 msvcrt.kbhit(),在 Unix 下使用 termios/tty/select 的 cbreak 模式,非终端环境则回退到线程化 input() 模式。

4.2 Profile 压缩(Shrink)

真实浏览产生的 profile 会累积大量缓存与历史数据。BrowserProfiler.shrink() 提供五级 ShrinkLevel(定义于 browser_profiler.py 顶部):

档位 保留内容
NONE 保留一切(默认)
LIGHT 仅删缓存,保留历史、书签、favicon 等
MEDIUM 缓存 + 历史/书签
AGGRESSIVE 仅保留鉴权数据(源码注释标记为推荐)
MINIMAL 仅 Cookie + localStorage

所有档位都会强制保留 storage_state.json,因为它对跨机器 profile 移植是必需的。压缩逻辑会先探测 Default/ 子目录(Chrome profile 数据通常在其中),按 KEEP_PATTERNS 白名单逐项保留或删除,并返回包含 removedkeptbytes_freedsize_beforesize_after 的报告;dry_run=True 时只预览不删除。该能力有对应测试 test_profile_shrink.py

4.3 交互式管理控制台

BrowserProfiler 还提供一个交互式管理控制台,引导你完成创建、列表、删除操作:

import asyncio
from crawl4ai import BrowserProfiler, AsyncWebCrawler, BrowserConfig

# 定义一个使用 profile 爬取的函数
async def crawl_with_profile(profile_path, url):
    browser_config = BrowserConfig(
        headless=True,
        use_managed_browser=True,
        user_data_dir=profile_path
    )

    async with AsyncWebCrawler(config=browser_config) as crawler:
        result = await crawler.arun(url)
        return result

async def main():
    profiler = BrowserProfiler()

    # 启动交互式 profile 管理器
    # 传入 crawl 回调后,菜单会多出"使用该 profile 爬取"选项
    await profiler.interactive_manager(crawl_callback=crawl_with_profile)

asyncio.run(main())

interactive_manager(crawl_callback) 的菜单为:1. 创建新 profile(回车可自动生成时间戳命名);2. 列出 profile;3. 删除 profile(带二次确认);4/5. 当传入了 crawl_callback 时,多出“选一个 profile + 输入 URL 立即爬取”的选项,回调以 (profile_path, url) 调用。

4.4 旧接口兼容

出于向后兼容,ManagedBrowser 上原有的静态方法仍然可用,但内部全部委托给 BrowserProfiler(见 browser_manager.pycreate_profile / list_profiles / delete_profile 的文档字符串):

from crawl4ai.browser_manager import ManagedBrowser

# 这些方法仍然有效,但内部使用 BrowserProfiler
profiles = ManagedBrowser.list_profiles()

4.5 完整示例与相关测试

完整的使用示例见 identity_based_browsing.py,演示了创建 profile 并使用其进行认证浏览的端到端流程。相关测试用例包括 test_create_profile.pytest_profiles.pytest_profile_shrink.py,可作为行为基准参考。

5. Magic Mode:无持久化的轻量自动化

如果你不需要持久化 profile 或身份化方案,Magic Mode 提供了快速模拟类人浏览的方式,不存储任何长期数据:

from crawl4ai import AsyncWebCrawler, CrawlerRunConfig

async with AsyncWebCrawler() as crawler:
    result = await crawler.arun(
        url="https://example.com",
        config=CrawlerRunConfig(
            magic=True,  # Simplifies a lot of interaction
            remove_overlay_elements=True,
            page_timeout=60000
        )
    )

Magic Mode 的行为:

  • 模拟类人用户体验;
  • 随机化 User-Agent 与 navigator 信息;
  • 随机化交互与操作时序;
  • 掩盖自动化信号;
  • 尝试处理弹窗。

CrawlerRunConfig 中,magic 参数默认值为 Falseasync_configs.py 的参数说明将其定位为“自动处理 overlays/popups 的开关”。注意:Magic Mode 不是真实用户会话的替代品——如果需要完全合法的身份化方案,请使用 Managed Browsers。

6. 对比:Managed Browsers vs Magic Mode

特性 Managed Browsers Magic Mode
会话持久化 user_data_dir 中完整保留 localStorage/cookies 无持久数据(每次全新开始)
真实身份 带完整权限与偏好的真实用户 profile 仅模拟类人行为,无真实身份
复杂站点 最适合登录受限站点或重配置场景 简单任务,基本无登录或配置需求
搭建成本 需先外部创建 user_data_dir,再交给 Crawl4AI 单行配置(magic=True
可靠性 极高(各次运行数据一致) 小任务表现良好,稳定性可能稍弱

7. 语言、时区与地理位置控制

除了复用持久化 profile,Crawl4AI 还支持定制浏览器的 locale、时区与地理位置,用于控制网站对你“地域身份”的感知。

7.1 设置 Locale 与时区

通过 CrawlerRunConfig 设置:

from crawl4ai import AsyncWebCrawler, CrawlerRunConfig

async with AsyncWebCrawler() as crawler:
    result = await crawler.arun(
        url="https://example.com",
        config=CrawlerRunConfig(
            # 设置浏览器 locale(语言与区域格式)
            locale="fr-FR",  # 法语(法国)

            # 设置浏览器时区
            timezone_id="Europe/Paris",

            # 其他常规选项……
            magic=True,
            page_timeout=60000
        )
    )

工作机制:

  • locale 影响语言偏好、日期格式、数字格式等;
  • timezone_id 影响 JavaScript 的 Date 对象及一切时间相关功能;
  • 两者在创建浏览器 context 时应用,并在整个会话期间维持。

async_configs.py 中,CrawlerRunConfig 声明了 locale(如 "en-US")、timezone_id(如 "America/New_York")与 geolocation 三个字段,并参与配置序列化(to_dict),因此也支持跨进程/远程场景传递。

7.2 配置地理位置

控制浏览器 Geolocation API 上报的 GPS 坐标:

from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, GeolocationConfig

async with AsyncWebCrawler() as crawler:
    result = await crawler.arun(
        url="https://maps.google.com",  # 或任何依赖位置的站点
        config=CrawlerRunConfig(
            # 配置精确 GPS 坐标
            geolocation=GeolocationConfig(
                latitude=48.8566,   # 巴黎坐标
                longitude=2.3522,
                accuracy=100        # 精度(米),可选
            ),

            # 该站点会认为你在巴黎
            page_timeout=60000
        )
    )

要点:

  • 指定 geolocation 后,浏览器会被自动授予位置访问权限;
  • 使用 Geolocation API 的网站将收到你指定的精确坐标;
  • 影响地图服务、门店定位、配送服务等;
  • 与恰当的 localetimezone_id 组合,可构建完全自洽的位置画像。

GeolocationConfig 定义于 async_configs.pylatitudelongitude 为必填浮点坐标,accuracy 表示精度(米),默认 0.0

7.3 与 Managed Browsers 组合:完整身份方案

这些设置与托管浏览器配合,构成完整的身份解决方案:

from crawl4ai import (
    AsyncWebCrawler, BrowserConfig, CrawlerRunConfig,
    GeolocationConfig
)

browser_config = BrowserConfig(
    use_managed_browser=True,
    user_data_dir="/path/to/my-profile",
    browser_type="chromium"
)

crawl_config = CrawlerRunConfig(
    # 位置相关设置
    locale="es-MX",                  # 西班牙语(墨西哥)
    timezone_id="America/Mexico_City",
    geolocation=GeolocationConfig(
        latitude=19.4326,            # 墨西哥城
        longitude=-99.1332
    )
)

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

持久化 profile + 精确地理信息 + 区域语言设置,三者组合即构成对数字身份的完全控制。

8. 小结

  • 创建 user-data 目录的三条路径:
    • 外部启动 Chrome/Chromium 并带 --user-data-dir=/some/path
    • BrowserProfiler.create_profile()(或 crwl profiles CLI);
    • profiler.interactive_manager() 交互界面。
  • 登录或按需配置站点,然后关闭浏览器;
  • 将该目录引用到 BrowserConfig(user_data_dir="...", use_managed_browser=True)
  • 定制身份维度:localetimezone_idgeolocation
  • 列出与复用 profile:BrowserProfiler.list_profiles()get_profile_path()
  • 管理 profile:删除(delete_profile)、压缩瘦身(shrinkAGGRESSIVE 档位在保留鉴权数据的前提下释放空间);
  • 享受与你真实身份一致的持久化会话,无需重复登录;
  • 若只需要快速、临时的自动化,Magic Mode 即可胜任。

推荐实践:对于稳健的身份化爬虫与复杂站点的交互,始终优先选择 Managed BrowsersMagic Mode 适合无需持久化数据的快速任务与原型验证。通过上述方式,你可以维持一个真实的浏览环境,让站点看到的你与普通用户无异——没有重复登录,没有浪费时间。

登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起
kernelkernel
deepin linux kernel
C
33
18
ops-transformerops-transformer
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
1.12 K
2.72 K
kernelkernel
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
527
590
ops-nnops-nn
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
904
1.82 K
pytorchpytorch
作为 Ascend for PyTorch 社区的核心组件,TorchNPU 是昇腾专为 PyTorch 打造的深度学习适配插件,使 PyTorch 框架能够直接调用昇腾 NPU,为开发者提供昇腾 AI 处理器的超强算力。
Python
854
1.34 K
docsdocs
暂无描述
Markdown
889
5.78 K
jiuwenswarmjiuwenswarm
JiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。
Python
3.52 K
1.01 K
ops-mathops-math
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.33 K
1.45 K
cann-learning-hubcann-learning-hub
CANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。
Jupyter Notebook
982
502
AscendNPU-IRAscendNPU-IR
AscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优
C++
540
384