网络请求和控制台消息捕获
Crawl4AI 可以捕获爬网期间的所有网络请求和浏览器控制台消息,这对于调试、安全分析或了解页面行为非常有价值。
配置
要启用网络和控制台捕获,请使用以下配置选项:
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
# Enable both network request capture and console message capture
config = CrawlerRunConfig(
capture_network_requests=True, # Capture all network requests and responses
capture_console_messages=True # Capture all browser console output
)
示例用法
import asyncio
import json
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
async def main():
# Enable both network request capture and console message capture
config = CrawlerRunConfig(
capture_network_requests=True,
capture_console_messages=True
)
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://example.com",
config=config
)
if result.success:
# Analyze network requests
if result.network_requests:
print(f"Captured {len(result.network_requests)} network events")
# Count request types
request_count = len([r for r in result.network_requests if r.get("event_type") == "request"])
response_count = len([r for r in result.network_requests if r.get("event_type") == "response"])
failed_count = len([r for r in result.network_requests if r.get("event_type") == "request_failed"])
print(f"Requests: {request_count}, Responses: {response_count}, Failed: {failed_count}")
# Find API calls
api_calls = [r for r in result.network_requests
if r.get("event_type") == "request" and "api" in r.get("url", "")]
if api_calls:
print(f"Detected {len(api_calls)} API calls:")
for call in api_calls[:3]: # Show first 3
print(f" - {call.get('method')} {call.get('url')}")
# Analyze console messages
if result.console_messages:
print(f"Captured {len(result.console_messages)} console messages")
# Group by type
message_types = {}
for msg in result.console_messages:
msg_type = msg.get("type", "unknown")
message_types[msg_type] = message_types.get(msg_type, 0) + 1
print("Message types:", message_types)
# Show errors (often the most important)
errors = [msg for msg in result.console_messages if msg.get("type") == "error"]
if errors:
print(f"Found {len(errors)} console errors:")
for err in errors[:2]: # Show first 2
print(f" - {err.get('text', '')[:100]}")
# Export all captured data to a file for detailed analysis
with open("network_capture.json", "w") as f:
json.dump({
"url": result.url,
"network_requests": result.network_requests or [],
"console_messages": result.console_messages or []
}, f, indent=2)
print("Exported detailed capture data to network_capture.json")
if __name__ == "__main__":
asyncio.run(main())
捕获的数据结构
网络请求
这result.network_requests
包含一个字典列表,每个字典代表一个具有以下公共字段的网络事件:
场地 | 描述 |
---|---|
event_type |
活动类型:"request" ,"response" , 或者"request_failed" |
url |
请求的 URL |
timestamp |
捕获事件时的 Unix 时间戳 |
请求事件字段
{
"event_type": "request",
"url": "https://example.com/api/data.json",
"method": "GET",
"headers": {"User-Agent": "...", "Accept": "..."},
"post_data": "key=value&otherkey=value",
"resource_type": "fetch",
"is_navigation_request": false,
"timestamp": 1633456789.123
}
响应事件字段
{
"event_type": "response",
"url": "https://example.com/api/data.json",
"status": 200,
"status_text": "OK",
"headers": {"Content-Type": "application/json", "Cache-Control": "..."},
"from_service_worker": false,
"request_timing": {"requestTime": 1234.56, "receiveHeadersEnd": 1234.78},
"timestamp": 1633456789.456
}
失败请求事件字段
{
"event_type": "request_failed",
"url": "https://example.com/missing.png",
"method": "GET",
"resource_type": "image",
"failure_text": "net::ERR_ABORTED 404",
"timestamp": 1633456789.789
}
控制台消息
这result.console_messages
包含一个字典列表,每个字典代表一个具有以下公共字段的控制台消息:
场地 | 描述 |
---|---|
type |
消息类型:"log" ,"error" ,"warning" ,"info" , ETC。 |
text |
消息文本 |
timestamp |
捕获消息时的 Unix 时间戳 |
控制台消息示例
{
"type": "error",
"text": "Uncaught TypeError: Cannot read property 'length' of undefined",
"location": "https://example.com/script.js:123:45",
"timestamp": 1633456790.123
}
主要优点
- 完整请求可见性:捕获所有网络活动,包括:
- 请求(URL、方法、标头、发布数据)
- 响应(状态代码、标题、时间)
- 失败的请求(带有错误消息)
- 控制台消息访问:查看所有 JavaScript 控制台输出:
- 日志消息
- 警告
- 堆栈跟踪错误
- 开发人员调试信息
- 调试能力:识别以下问题:
- API 调用或资源加载失败
- 影响页面功能的 JavaScript 错误
- CORS 或其他安全问题
- 隐藏的 API 端点和数据流
- 安全分析:检测:
- 意外的第三方请求
- 请求有效负载中的数据泄漏
- 可疑脚本行为
- 性能洞察:分析:
- 请求时间数据
- 资源加载模式
- 潜在的瓶颈
用例
- API 发现:识别单页应用程序中的隐藏端点和数据流
- 调试:追踪影响页面功能的 JavaScript 错误
- 安全审计:检测不需要的第三方请求或数据泄露
- 性能分析:识别加载缓慢的资源
- 广告/跟踪器分析:检测并分类广告或跟踪电话
此功能对于具有大量 JavaScript、单页应用程序的复杂站点尤其有价值,或者当您需要了解浏览器和服务器之间发生的确切通信时。