使用 Crawl4AI 保护您的身份

Crawl4AI 让您能够使用真实的数字身份浏览网页并进行互动,确保您被识别为人类,而不会被误认为是机器人。本教程涵盖以下内容:

1. 托管浏览器 – 推荐用于持久配置文件和基于身份的抓取的方法。2. 魔法模式 – 一种简化的回退解决方案,无需持久身份即可快速实现自动化。


1. 托管浏览器:您的数字身份解决方案

托管浏览器允许开发者创建并使用持久性浏览器配置文件。这些配置文件存储本地存储、Cookie 和其他会话数据,让您能够以真实的身份进行浏览,包括登录信息、偏好设置和 Cookie。

主要优点

  • 真实的浏览体验:保留会话数据和浏览器指纹,就像您是普通用户一样。
  • 轻松配置:一旦您登录或在所选数据目录中解决验证码,您就可以重新运行爬网,而无需重复这些步骤。
  • 授权数据访问:如果您可以在自己的浏览器中看到数据,则可以使用您的真实身份自动检索数据。

以下是托管浏览器教程的部分更新,特别是关于使用 Playwright 的 Chromium 二进制文件(而非系统级 Chrome/Edge)创建用户数据目录的部分。我们将演示如何找到该二进制文件并使用--user-data-dir参数来设置您的个人资料。然后您可以指向BrowserConfig.user_data_dir到该文件夹以供后续抓取。


创建用户数据目录(通过 Playwright 的命令行方法)

如果您安装了 Crawl4AI(它会在后台安装 Playwright),那么您的系统上已经有一个由 Playwright 管理的 Chromium。请按照以下步骤从命令行启动该 Chromium,并指定一个自定义数据目录:

1. 找到 Playwright Chromium 二进制文件: - 在大多数系统上,已安装的浏览器位于~/.cache/ms-playwright/文件夹或类似路径。 - 要查看已安装浏览器的概览,请运行:

python -m playwright install --dry-run
or
playwright install --dry-run
(depending on your environment). This shows where Playwright keeps Chromium.

  • 例如,您可能会看到如下路径:
    ~/.cache/ms-playwright/chromium-1234/chrome-linux/chrome
    
    在 Linux 上,或者在 macOS/Windows 上相应的文件夹。

2. 使用自定义用户数据目录启动 Playwright Chromium 二进制文件:

# Linux example
~/.cache/ms-playwright/chromium-1234/chrome-linux/chrome \
    --user-data-dir=/home/<you>/my_chrome_profile
# macOS example (Playwright’s internal binary)
~/Library/Caches/ms-playwright/chromium-1234/chrome-mac/Chromium.app/Contents/MacOS/Chromium \
    --user-data-dir=/Users/<you>/my_chrome_profile
# Windows example (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缓存结构。 - 这将打开一个新的 Chromium,其中包含您的新数据文件夹或现有数据文件夹。 - 登录任何网站或按您想要的方式配置浏览器。 - 完成后关闭 - 您的个人资料数据保存在该文件夹中。

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"
)
- Next time you run your code, it reuses that folder—preserving your session data, cookies, local storage, etc.


3. 在 Crawl4AI 中使用托管浏览器

一旦你有了包含会话数据的数据目录,将其传递给BrowserConfig

import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig

async def main():
    # 1) Reference your persistent data directory
    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) Standard crawl config
    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())

工作流程

1. 从外部登录(通过 CLI 或普通的 Chrome 浏览器)--user-data-dir=... )。2. 关闭该浏览器。3. 使用相同的文件夹user_data_dir=在 Crawl4AI 中。4. Crawl – 网站会将您的身份视为刚刚登录的用户。


4.魔法模式:简化自动化

如果您不需要持久配置文件或基于身份的方法,魔法模式提供了一种快速的方法来模拟类似人类的浏览,而无需存储长期数据。

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

魔法模式:

  • 模拟用户体验
  • 随机化用户代理和导航器
  • 随机化互动和时间
  • 屏蔽自动化信号
  • 尝试弹出处理

但如果您想要一个完全合法的基于身份的解决方案,它就不能替代真正的基于用户的会话。


5. 比较托管浏览器与魔法模式

特征 托管浏览器 魔法模式
会话持久性 完整的 localStorage/cookies 保留在 user_data_dir 中 没有持久数据(每次运行都更新)
真实身份 具有完整权利和偏好的真实用户资料 模拟用户模式,但没有实际身份
复杂场地 最适合登录门控网站或配置繁重的网站 简单的任务,只需最少的登录或配置
设置 外部创建 user_data_dir,然后在 Crawl4AI 中使用 单线方法(magic=True )
可靠性 极其一致(多次运行的数据相同) 适合较小的任务,但稳定性较差

6. 使用 BrowserProfiler 类

Crawl4AI 提供专用BrowserProfiler用于管理浏览器配置文件的类,可以轻松创建、列出和删除基于身份的浏览的配置文件。

使用 BrowserProfiler 创建和管理配置文件

BrowserProfiler该类为浏览器配置文件管理提供了全面的 API:

import asyncio
from crawl4ai import BrowserProfiler

async def manage_profiles():
    # Create a profiler instance
    profiler = BrowserProfiler()

    # Create a profile interactively - opens a browser window
    profile_path = await profiler.create_profile(
        profile_name="my-login-profile"  # Optional: name your profile
    )

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

    # List all available profiles
    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']}")

    # Get a specific profile path by name
    specific_profile = profiler.get_profile_path("my-login-profile")

    # Delete a profile when no longer needed
    success = profiler.delete_profile("old-profile-name")

asyncio.run(manage_profiles())

配置文件创建的工作方式:1. 打开一个浏览器窗口供您交互 2. 登录网站、设置首选项等。3. 完成后,在终端中按“q”关闭浏览器 4. 配置文件保存在 Crawl4AI 配置文件目录中 5. 您可以使用返回的路径BrowserConfig.user_data_dir

交互式配置文件管理

BrowserProfiler还提供了一个交互式管理控制台,指导您完成配置文件的创建、列出和删除:

import asyncio
from crawl4ai import BrowserProfiler, AsyncWebCrawler, BrowserConfig

# Define a function to use a profile for crawling
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():
    # Create a profiler instance
    profiler = BrowserProfiler()

    # Launch the interactive profile manager
    # Passing the crawl function as a callback adds a "crawl with profile" option
    await profiler.interactive_manager(crawl_callback=crawl_with_profile)

asyncio.run(main())

遗留方法

为了向后兼容,以前的方法ManagedBrowser仍然可用,但他们委托给新的BrowserProfiler班级:

from crawl4ai.browser_manager import ManagedBrowser

# These methods still work but use BrowserProfiler internally
profiles = ManagedBrowser.list_profiles()

完整示例

请参阅完整示例docs/examples/identity_based_browsing.py完整演示如何使用新的BrowserProfiler班级。


7. 区域设置、时区和地理位置控制

除了使用持久配置文件外,Crawl4AI 还支持自定义浏览器的语言环境、时区和地理位置设置。这些功能允许您控制网站如何感知您的位置和区域设置,从而增强您基于身份的浏览体验。

设置区域设置和时区

您可以通过以下方式设置浏览器的语言环境和时区CrawlerRunConfig

from crawl4ai import AsyncWebCrawler, CrawlerRunConfig

async with AsyncWebCrawler() as crawler:
    result = await crawler.arun(
        url="https://example.com",
        config=CrawlerRunConfig(
            # Set browser locale (language and region formatting)
            locale="fr-FR",  # French (France)

            # Set browser timezone
            timezone_id="Europe/Paris",

            # Other normal options...
            magic=True,
            page_timeout=60000
        )
    )

工作原理:-locale影响语言偏好、日期格式、数字格式等 -timezone_id影响 JavaScript 的 Date 对象和时间相关功能 - 这些设置在创建浏览器上下文时应用,并在整个会话期间保持

配置地理位置

控制浏览器地理位置 API 报告的 GPS 坐标:

from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, GeolocationConfig

async with AsyncWebCrawler() as crawler:
    result = await crawler.arun(
        url="https://maps.google.com",  # Or any location-aware site
        config=CrawlerRunConfig(
            # Configure precise GPS coordinates
            geolocation=GeolocationConfig(
                latitude=48.8566,   # Paris coordinates
                longitude=2.3522,
                accuracy=100        # Accuracy in meters (optional)
            ),

            # This site will see you as being in Paris
            page_timeout=60000
        )
    )

重要提示:- 当geolocation指定后,浏览器将自动获得访问位置的权限 - 使用地理定位 API 的网站将收到您指定的精确坐标 - 这会影响地图服务、商店定位器、送货服务等 - 结合适当的localetimezone_id,您可以创建完全一致的位置配置文件

与托管浏览器结合

这些设置与托管浏览器完美配合,可提供完整的身份解决方案:

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(
    # Location settings
    locale="es-MX",                  # Spanish (Mexico)
    timezone_id="America/Mexico_City",
    geolocation=GeolocationConfig(
        latitude=19.4326,            # Mexico City
        longitude=-99.1332
    )
)

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

将持久的配置文件与精确的地理位置和区域设置相结合,可以让您完全控制您的数字身份。

8.总结

  • 创建您的用户数据目录:
  • 通过外部启动 Chrome/Chromium--user-data-dir=/some/path
  • 或者使用内置BrowserProfiler.create_profile()方法
  • 或者通过交互界面profiler.interactive_manager()
  • 根据需要登录或配置站点,然后关闭浏览器
  • 引用该文件夹BrowserConfig(user_data_dir="...")+use_managed_browser=True
  • 自定义身份方面localetimezone_id , 和geolocation
  • 列出并重复使用配置文件BrowserProfiler.list_profiles()
  • 使用专用的BrowserProfiler班级
  • 享受反映您真实身份的持续会话
  • 如果你只需要快速、短暂的自动化,魔法模式可能就足够了

建议:始终优先使用托管浏览器,以实现基于身份的稳健抓取,并简化与复杂网站的交互。对于不需要持久数据的快速任务或原型设计,请使用魔法模式。

通过这些方法,您可以保留真实的浏览环境,确保网站将您视为普通用户 - 无需重复登录或浪费时间。


> Feedback