docs/CDP模式使用指南.md
CDP(Chrome DevTools Protocol)模式是一种高级的反检测爬虫技术,通过控制用户现有的Chrome/Edge浏览器来进行网页爬取。与传统的Playwright自动化相比,CDP模式具有以下优势:
在 config/base_config.py 中设置:
# 启用CDP模式
ENABLE_CDP_MODE = True
# CDP调试端口(可选,默认9222)
CDP_DEBUG_PORT = 9222
# 是否在无头模式下运行(建议设为False以获得最佳反检测效果)
CDP_HEADLESS = False
# 程序结束时是否自动关闭浏览器
AUTO_CLOSE_BROWSER = True
# 运行CDP功能测试
python examples/cdp_example.py
# 运行小红书爬虫(CDP模式)
python main.py
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
ENABLE_CDP_MODE | bool | False | 是否启用CDP模式 |
CDP_DEBUG_PORT | int | 9222 | CDP调试端口 |
CDP_HEADLESS | bool | False | CDP模式下的无头模式 |
AUTO_CLOSE_BROWSER | bool | True | 程序结束时是否关闭浏览器 |
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
CUSTOM_BROWSER_PATH | str | "" | 自定义浏览器路径 |
BROWSER_LAUNCH_TIMEOUT | int | 30 | 浏览器启动超时时间(秒) |
如果系统自动检测失败,可以手动指定浏览器路径:
# Windows示例
CUSTOM_BROWSER_PATH = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
# macOS示例
CUSTOM_BROWSER_PATH = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
# Linux示例
CUSTOM_BROWSER_PATH = "/usr/bin/google-chrome"
import asyncio
from playwright.async_api import async_playwright
from tools.cdp_browser import CDPBrowserManager
async def main():
cdp_manager = CDPBrowserManager()
async with async_playwright() as playwright:
# 启动CDP浏览器
browser_context = await cdp_manager.launch_and_connect(
playwright=playwright,
user_agent="自定义User-Agent",
headless=False
)
# 创建页面并访问网站
page = await browser_context.new_page()
await page.goto("https://example.com")
# 执行爬取操作...
# 清理资源
await cdp_manager.cleanup()
asyncio.run(main())
CDP模式已集成到所有平台爬虫中,只需启用配置即可:
# 在config/base_config.py中
ENABLE_CDP_MODE = True
# 然后正常运行爬虫
python main.py
错误: 未找到可用的浏览器
解决方案:
CUSTOM_BROWSER_PATH指定浏览器路径错误: 无法找到可用的端口
解决方案:
CDP_DEBUG_PORT为其他端口错误: 浏览器在30秒内未能启动
解决方案:
BROWSER_LAUNCH_TIMEOUT值错误: CDP连接失败
解决方案:
import logging
logging.basicConfig(level=logging.DEBUG)
# 手动启动Chrome
chrome --remote-debugging-port=9222
# 访问调试页面
curl http://localhost:9222/json
# Windows
tasklist | findstr chrome
# macOS/Linux
ps aux | grep chrome
CDP_HEADLESS = False以获得最佳反检测效果AUTO_CLOSE_BROWSERCDP模式的工作原理:
--remote-debugging-port参数启动浏览器connectOverCDP方法接管浏览器控制这种方式绕过了传统WebDriver的检测机制,提供了更加隐蔽的自动化能力。
欢迎提交Issue和Pull Request来改进CDP模式功能。
本功能遵循项目的整体许可证条款,仅供学习和研究使用。