参考
这CrawlResult
该类封装了单次爬取操作后返回的所有内容。它提供原始或处理后的内容、链接和媒体的详细信息,以及可选的元数据(例如屏幕截图、PDF 或提取的 JSON)。
地点:crawl4ai/crawler/models.py
(仅供参考)
class CrawlResult(BaseModel):
url: str
html: str
success: bool
cleaned_html: Optional[str] = None
fit_html: Optional[str] = None # Preprocessed HTML optimized for extraction
media: Dict[str, List[Dict]] = {}
links: Dict[str, List[Dict]] = {}
downloaded_files: Optional[List[str]] = None
screenshot: Optional[str] = None
pdf : Optional[bytes] = None
mhtml: Optional[str] = None
markdown: Optional[Union[str, MarkdownGenerationResult]] = None
extracted_content: Optional[str] = None
metadata: Optional[dict] = None
error_message: Optional[str] = None
session_id: Optional[str] = None
response_headers: Optional[dict] = None
status_code: Optional[int] = None
ssl_certificate: Optional[SSLCertificate] = None
dispatch_result: Optional[DispatchResult] = None
...
以下是逐个字段的解释和可能的使用模式。
1. 基本爬取信息
1.1url
(字符串)
内容:最终抓取的 URL(任何重定向之后)。用法:
1.2success
(布尔值)
什么:True
如果爬取管道结束时没有出现重大错误;False
否则。用法:
1.3status_code
(可选[int])
内容:页面的 HTTP 状态代码(例如 200、404)。用法:
1.4error_message
(可选[str])
如果什么success=False
,失败的文本描述。用法:
1.5session_id
(可选[str])
含义:用于在多个调用之间重复使用浏览器上下文的 ID。用法:
# If you used session_id="login_session" in CrawlerRunConfig, see it here:
print("Session:", result.session_id)
1.6response_headers
(可选[dict])
内容:最终 HTTP 响应标头。用法:
1.7ssl_certificate
(可选[SSL证书])
如果什么fetch_ssl_certificate=True
在你的 CrawlerRunConfig 中,result.ssl_certificate
包含一个SSLCertificate
描述站点证书的对象。您可以以多种格式(PEM/DER/JSON)导出证书,或访问其属性,例如issuer
,subject
,valid_from
,valid_until
等用法:
2. 原始/清理后的内容
2.1html
(字符串)
内容:最终页面加载时未修改的原始 HTML。用法:
2.2cleaned_html
(可选[str])
内容:经过清理的 HTML 版本——根据您的CrawlerRunConfig
。 用法:
3. Markdown 字段
3.1 Markdown 生成方法
Crawl4AI 可以将 HTML 转换为 Markdown,可选包括:
- 原始降价
- 链接作为引用(带有参考部分)
- 如果使用内容过滤器(如 Pruning 或 BM25),则适合 markdown
包括:-raw_markdown
(str): 完整的 HTML→Markdown 转换。 -markdown_with_citations
(str): 相同的 markdown,但使用链接引用作为学术风格的引用。 -references_markdown
(str): 最后的参考列表或脚注。 -fit_markdown
(可选[str]):如果应用了内容过滤(修剪/BM25),则过滤后的“适合”文本。 -fit_html
(可选[str]): 导致fit_markdown
。
用法:
if result.markdown:
md_res = result.markdown
print("Raw MD:", md_res.raw_markdown[:300])
print("Citations MD:", md_res.markdown_with_citations[:300])
print("References:", md_res.references_markdown)
if md_res.fit_markdown:
print("Pruned text:", md_res.fit_markdown[:300])
3.2markdown
(可选[Union[str,MarkdownGenerationResult]])
什么:拥有MarkdownGenerationResult
。 用法:
print(result.markdown.raw_markdown[:200])
print(result.markdown.fit_markdown)
print(result.markdown.fit_html)
fit_markdown
/fit_html
) exists in result.markdown, only if you used a filter (like PruningContentFilter or BM25ContentFilter) within a MarkdownGenerationStrategy
.
4.媒体与链接
4.1media
(字典[str,列表[字典]])
内容:包含已发现图像、视频或音频的信息。通常包含以下键:"images"
,"videos"
,"audios"
. 每个项目中的公共字段:
- (str): 媒体 URL
- 或者
title
(str): 描述性文本 - (浮点数):如果爬虫的启发式方法发现它“重要”,则相关性得分
- 或者
description
(可选[str]):从周围文本中提取的附加上下文
用法:
images = result.media.get("images", [])
for img in images:
if img.get("score", 0) > 5:
print("High-value image:", img["src"])
4.2links
(字典[str,列表[字典]])
内容:保存内部和外部链接数据。通常包含两个键:"internal"
和"external"
. 常用字段:
- (str): 链接目标
- (str): 链接文本
- (str): 标题属性
- (str): 周围的文本片段
- (str): 如果是外部的,则域
用法:
for link in result.links["internal"]:
print(f"Internal link to {link['href']} with text {link['text']}")
5.附加字段
5.1extracted_content
(可选[str])
什么:如果你使用extraction_strategy
(CSS、LLM等),结构化输出(JSON)。用法:
5.2downloaded_files
(可选[列表[字符串]])
如果什么accept_downloads=True
在你的BrowserConfig
+downloads_path
,列出下载项目的本地文件路径。用法:
if result.downloaded_files:
for file_path in result.downloaded_files:
print("Downloaded:", file_path)
5.3screenshot
(可选[str])
内容:Base64 编码的屏幕截图screenshot=True
在CrawlerRunConfig
。 用法:
import base64
if result.screenshot:
with open("page.png", "wb") as f:
f.write(base64.b64decode(result.screenshot))
5.4pdf
(可选[字节])
内容:原始 PDF 字节(如果)pdf=True
在CrawlerRunConfig
。 用法:
5.5mhtml
(可选[str])
什么:页面的 MHTML 快照capture_mhtml=True
在CrawlerRunConfig
。MHTML(MIME HTML)格式将整个网页及其所有资源(CSS、图像、脚本等)保存在一个文件中。用法:
5.6metadata
(可选[dict])
内容:页面级元数据(如果发现)(标题、描述、OG 数据等)。用法:
if result.metadata:
print("Title:", result.metadata.get("title"))
print("Author:", result.metadata.get("author"))
6.dispatch_result
(选修的)
一个DispatchResult
对象在并行抓取 URL 时提供额外的并发和资源使用信息(例如通过arun_many()
使用自定义调度程序)。它包含:
- :并行任务的唯一标识符。
- (浮点数):完成时使用的内存(以 MB 为单位)。
- (浮点数):任务执行期间记录的峰值内存使用量(以 MB 为单位)。
- /
end_time
(datetime):本次爬取任务的时间范围。 - (str):遇到的任何与调度程序或并发相关的错误。
# Example usage:
for result in results:
if result.success and result.dispatch_result:
dr = result.dispatch_result
print(f"URL: {result.url}, Task ID: {dr.task_id}")
print(f"Memory: {dr.memory_usage:.1f} MB (Peak: {dr.peak_memory:.1f} MB)")
print(f"Duration: {dr.end_time - dr.start_time}")
注意:此字段通常在使用时填充arun_many(...)
与调度员一起(例如,MemoryAdaptiveDispatcher
或者SemaphoreDispatcher
)。如果没有使用并发或调度程序,dispatch_result
可能会保留None
。
7. 网络请求和控制台消息
当您启用网络和控制台消息捕获时CrawlerRunConfig
使用capture_network_requests=True
和capture_console_messages=True
, 这CrawlResult
将包括以下字段:
7.1network_requests
(可选[列表[字典[str,任意]]])
内容:包含抓取过程中捕获的所有网络请求、响应和故障信息的字典列表。结构:- 每项都有一个event_type
可以"request"
,"response"
, 或者"request_failed"
.- 请求事件包括url
,method
,headers
,post_data
,resource_type
, 和is_navigation_request
.- 响应事件包括url
,status
,status_text
,headers
, 和request_timing
.- 失败请求事件包括url
,method
,resource_type
, 和failure_text
. - 所有活动均包含timestamp
场地。
用法:
if result.network_requests:
# Count different types of events
requests = [r for r in result.network_requests if r.get("event_type") == "request"]
responses = [r for r in result.network_requests if r.get("event_type") == "response"]
failures = [r for r in result.network_requests if r.get("event_type") == "request_failed"]
print(f"Captured {len(requests)} requests, {len(responses)} responses, and {len(failures)} failures")
# Analyze API calls
api_calls = [r for r in requests if "api" in r.get("url", "")]
# Identify failed resources
for failure in failures:
print(f"Failed to load: {failure.get('url')} - {failure.get('failure_text')}")
7.2console_messages
(可选[列表[字典[str,任意]]])
内容:包含抓取过程中捕获的所有浏览器控制台消息的字典列表。结构:- 每项都有一个type
指示消息类型的字段(例如,"log"
,"error"
,"warning"
等)。——text
字段包含实际的消息文本。 - 一些消息包括location
信息(URL、行、列)。- 所有消息都包含timestamp
场地。
用法:
if result.console_messages:
# Count messages 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(f"Message type counts: {message_types}")
# Display errors (which are usually most important)
for msg in result.console_messages:
if msg.get("type") == "error":
print(f"Error: {msg.get('text')}")
这些字段提供了对页面网络活动和浏览器控制台的深入可见性,这对于调试、安全分析和理解复杂的 Web 应用程序非常有价值。
有关网络和控制台捕获的更多详细信息,请参阅网络和控制台捕获文档。
8.示例:访问所有内容
async def handle_result(result: CrawlResult):
if not result.success:
print("Crawl error:", result.error_message)
return
# Basic info
print("Crawled URL:", result.url)
print("Status code:", result.status_code)
# HTML
print("Original HTML size:", len(result.html))
print("Cleaned HTML size:", len(result.cleaned_html or ""))
# Markdown output
if result.markdown:
print("Raw Markdown:", result.markdown.raw_markdown[:300])
print("Citations Markdown:", result.markdown.markdown_with_citations[:300])
if result.markdown.fit_markdown:
print("Fit Markdown:", result.markdown.fit_markdown[:200])
# Media & Links
if "images" in result.media:
print("Image count:", len(result.media["images"]))
if "internal" in result.links:
print("Internal link count:", len(result.links["internal"]))
# Extraction strategy result
if result.extracted_content:
print("Structured data:", result.extracted_content)
# Screenshot/PDF/MHTML
if result.screenshot:
print("Screenshot length:", len(result.screenshot))
if result.pdf:
print("PDF bytes length:", len(result.pdf))
if result.mhtml:
print("MHTML length:", len(result.mhtml))
# Network and console capturing
if result.network_requests:
print(f"Network requests captured: {len(result.network_requests)}")
# Analyze request types
req_types = {}
for req in result.network_requests:
if "resource_type" in req:
req_types[req["resource_type"]] = req_types.get(req["resource_type"], 0) + 1
print(f"Resource types: {req_types}")
if result.console_messages:
print(f"Console messages captured: {len(result.console_messages)}")
# Count by message type
msg_types = {}
for msg in result.console_messages:
msg_types[msg.get("type", "unknown")] = msg_types.get(msg.get("type", "unknown"), 0) + 1
print(f"Message types: {msg_types}")
9. 重点与未来
1. 弃用 CrawlResult 的旧属性 -markdown_v2
- 在 v0.5 中已弃用。只需使用markdown
。它拥有MarkdownGenerationResult
现在! -fit_markdown
和fit_html
- 在 v0.5 中已弃用。现在可以通过以下方式访问MarkdownGenerationResult
在result.markdown
例如:result.markdown.fit_markdown
和result.markdown.fit_html
2. 适合内容 -fit_markdown
和fit_html
仅当您在 MarkdownGenerationStrategy 中使用了内容过滤器(例如 PruningContentFilter 或 BM25ContentFilter)或直接设置它们时,它们才会出现在 MarkdownGenerationResult 中。 - 如果没有使用过滤器,它们将保留None
。
3. 参考文献和引文 - 如果您在DefaultMarkdownGenerator
(options={"citations": True}
),你会看到markdown_with_citations
加上references_markdown
块。这有助于大型语言模型或类似学术的引用。
4. 链接和媒体 -links["internal"]
和links["external"]
群组按域发现锚点。-media["images"]
/["videos"]
/["audios"]
存储提取的媒体元素以及可选的评分或上下文。
5. 错误案例 - 如果success=False
, 查看error_message
(例如,超时、无效的 URL)。-status_code
可能是None
如果我们在 HTTP 响应之前失败。
使用CrawlResult
收集所有最终输出并将其输入到数据管道、AI 模型或存档中。通过正确配置的 BrowserConfig 和 CrawlerRunConfig 的协同作用,爬虫可以生成稳健、结构化的结果CrawlResult
。