ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Crawl4AI CrawlResult 字段参考手册:从 HTML、Markdown 到网络事件的完整解析

Crawl4AI CrawlResult 字段参考手册:从 HTML、Markdown 到网络事件的完整解析 Crawl4AI CrawlResult 字段参考手册从 HTML、Markdown 到网络事件的完整解析【免费下载链接】crawl4ai Crawl4AI: Open-source LLM Friendly Web Crawler Scraper. Dont be shy, join here: https://discord.gg/jP8KfhDhyN项目地址: https://gitcode.com/GitHub_Trending/craw/crawl4ai本文以 Crawl4AI 官方文档docs/md_v2/api/crawl-result.md为主体系统讲解CrawlResult结果对象的每一个字段从基础爬取信息、原始/清洗 HTML、Markdown 生成结果、媒体与链接到截图、PDF、MHTML 快照、网络请求与控制台消息捕获并结合当前仓库源码crawl4ai/models.py、crawl4ai/async_configs.py、crawl4ai/async_crawler_strategy.py核实字段的真实定义、生成条件与底层实现。读完后你能够独立编写健壮的结果处理逻辑正确读取 Crawl4AI 任意一次爬取返回的结构化数据并将其送入数据管道或 AI 模型。1. CrawlResult 是什么单次爬取的完整交付单CrawlResult封装了单次爬取操作返回的一切内容原始或处理后的页面内容、链接与媒体明细以及可选的元数据截图、PDF、提取的 JSON 等。它是AsyncWebCrawler.arun()/arun_many()的核心返回值也是 Crawl4AI 与下游数据管道之间的标准接口。在源码中CrawlResult是一个 PydanticBaseModel定义于 crawl4ai/models.py官方文档标注的位置为crawl4ai/crawler/models.py当前仓库中已位于crawl4ai/models.py。其核心字段声明如下class CrawlResult(BaseModel): url: str html: str fit_html: Optional[str] None success: bool cleaned_html: Optional[str] None media: Dict[str, List[Dict]] {} links: Dict[str, List[Dict]] {} downloaded_files: Optional[List[str]] None js_execution_result: Optional[Dict[str, Any]] None screenshot: Optional[str] None pdf: Optional[bytes] None mhtml: Optional[str] None _markdown: Optional[MarkdownGenerationResult] PrivateAttr(defaultNone) 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 redirected_url: Optional[str] None redirected_status_code: Optional[int] None network_requests: Optional[List[Dict[str, Any]]] None console_messages: Optional[List[Dict[str, Any]]] None tables: List[Dict] Field(default_factorylist) # Cache validation metadata (Smart Cache) head_fingerprint: Optional[str] None cached_at: Optional[float] None cache_status: Optional[str] None # hit, hit_validated, hit_fallback, miss # Anti-bot retry/proxy usage stats crawl_stats: Optional[Dict[str, Any]] None model_config ConfigDict(arbitrary_types_allowedTrue)注意一个源码级细节markdown并不是普通字段而是一个由私有属性_markdown支撑的property见下文第 4 节。所有可选项字段在对应功能未启用时保持None因此处理结果时应始终以字段是否存在作为判断入口。1.1 字段与配置参数的对应关系速查结果字段由哪个配置控制配置所在类screenshotscreenshotTrueCrawlerRunConfigpdfpdfTrueCrawlerRunConfigmhtmlcapture_mhtmlTrueCrawlerRunConfigssl_certificatefetch_ssl_certificateTrueCrawlerRunConfignetwork_requestscapture_network_requestsTrueCrawlerRunConfigconsole_messagescapture_console_messagesTrueCrawlerRunConfigdownloaded_filesaccept_downloadsTruedownloads_pathBrowserConfigextracted_contentextraction_strategy...CrawlerRunConfigmarkdown.fit_markdown内容过滤器Pruning/BM25MarkdownGenerationStrategydispatch_resultarun_many(...) 调度器AsyncWebCrawler上述开关均定义在 crawl4ai/async_configs.py 中例如# CrawlerRunConfig.__init__ 中的相关参数crawl4ai/async_configs.py screenshot: bool False, pdf: bool False, capture_mhtml: bool False, capture_network_requests: bool False, capture_console_messages: bool False, fetch_ssl_certificate: bool False,而accept_downloads/downloads_path属于浏览器层配置定义在BrowserConfigcrawl4ai/async_configs.py。理解这一分层很重要页面产物截图、PDF、Markdown由每次请求的CrawlerRunConfig控制文件下载行为由一次性的BrowserConfig控制。2. 基础爬取信息字段2.1urlstr最终爬取的 URL经过重定向之后的地址。print(result.url) # e.g., https://example.com/2.2successbool爬取管道未发生重大错误时为True否则为False。它应是所有结果处理逻辑的第一道判断if not result.success: print(fCrawl failed: {result.error_message})2.3status_codeOptional[int]页面的 HTTP 状态码如 200、404。关键语义若页面是通过重定向到达的status_code记录的是重定向链中第一个响应的状态码例如 301 或 302。if result.status_code 404: print(Page not found!)2.4redirected_status_codeOptional[int]最终重定向目标的 HTTP 状态码。对于302 → 200的场景status_code是 302redirected_status_code是 200。对于非 HTTP 请求raw:原始 HTML、本地文件该值为None。配合源码中的redirected_url字段crawl4ai/models.py可以完整还原重定向链if result.status_code in (301, 302) and result.redirected_status_code 200: print(fRedirected to {result.redirected_url} (OK))这一对字段的区分对监控301/302 流量、识别失效链接、验证重定向策略都非常实用。2.5error_messageOptional[str]当successFalse时包含失败的文字描述超时、无效 URL、页面加载失败等。if not result.success: print(Error:, result.error_message)2.6session_idOptional[str]用于跨多次调用复用同一浏览器上下文的会话 ID。若你在CrawlerRunConfig中指定了session_idlogin_session这里会原样返回方便在批量任务中关联同一登录态print(Session:, result.session_id)2.7response_headersOptional[dict]最终 HTTP 响应头。可用于识别 WAF/CDNServer头、验证响应类型、做反爬策略调试if result.response_headers: print(Server:, result.response_headers.get(Server, Unknown))2.8ssl_certificateOptional[SSLCertificate]当CrawlerRunConfig中设置fetch_ssl_certificateTrue时result.ssl_certificate包含一个SSLCertificate对象描述站点证书信息。该对象支持多种格式导出PEM/DER/JSON并可访问issuer、subject、valid_from、valid_until等属性。SSLCertificate类定义在 crawl4ai/ssl_certificate.py更完整的用法见 SSL 证书文档if result.ssl_certificate: print(Issuer:, result.ssl_certificate.issuer)3. 原始与清洗后的内容3.1htmlstr原始、未经修改的最终页面 HTML。可能非常大注意内存占用print(len(result.html))3.2cleaned_htmlOptional[str]按照CrawlerRunConfig配置清洗过的 HTML——脚本、样式或被排除的标签已被移除print(result.cleaned_html[:500]) # Show a snippet3.3fit_htmlOptional[str]从源码结构看crawl4ai/models.pyfit_html是CrawlResult的顶层字段同时MarkdownGenerationResult内部也持有一份crawl4ai/models.py。它对应经过内容过滤Pruning/BM25后剩下的 HTML是fit_markdown的 HTML 源头。4. Markdown 字段与MarkdownGenerationResultCrawl4AI 支持 HTML → Markdown 转换可选地包含三种形态Rawmarkdown完整转换结果Links as citations链接改写为学术风格引用并附参考文献区Fitmarkdown当使用了内容过滤器Pruning 或 BM25时过滤后的贴合主题文本承载它们的模型是MarkdownGenerationResult源码定义见 crawl4ai/models.pyclass MarkdownGenerationResult(BaseModel): raw_markdown: str # 完整 HTML→Markdown 转换结果 markdown_with_citations: str # 链接改写为学术引用 references_markdown: str # 文末的引用列表/脚注 fit_markdown: Optional[str] None # 内容过滤Pruning/BM25后的文本 fit_html: Optional[str] None # 生成 fit_markdown 的 HTMLfit_markdown/fit_html只有在MarkdownGenerationStrategy中使用了内容过滤器如PruningContentFilter或BM25ContentFilter时才存在否则保持None。4.1 源码级实现markdown为什么既是字符串又是对象这是 Crawl4AI 一个非常巧妙的兼容性设计值得深入理解。result.markdown的类型标注为Optional[Union[str, MarkdownGenerationResult]]其背后实现crawl4ai/models.py分三层私有属性_markdown真正的存储位类型为MarkdownGenerationResultmarkdownproperty返回一个StringCompatibleMarkdown对象StringCompatibleMarkdownstr的子类内容取自raw_markdown同时通过__getattr__转发属性访问到内部的MarkdownGenerationResultclass StringCompatibleMarkdown(str): A string subclass that also provides access to MarkdownGenerationResult attributes def __new__(cls, markdown_result): return super().__new__(cls, markdown_result.raw_markdown) def __init__(self, markdown_result): self._markdown_result markdown_result def __getattr__(self, name): return getattr(self._markdown_result, name)这带来一个实战能力旧代码把result.markdown当字符串用拼接、写文件不会报错新代码又能通过result.markdown.fit_markdown访问结构化字段。此外model_dump()被覆写crawl4ai/models.py确保序列化输出中始终包含markdown键维持向后兼容。# 同一个表达式两种用法都成立 text result.markdown # 当字符串用内容是 raw_markdown fit result.markdown.fit_markdown # 当对象用访问结构化字段4.2 读取 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])如果启用了DefaultMarkdownGenerator的引用模式options{citations: True}生成器定义见 crawl4ai/markdown_generation_strategy.pymarkdown_with_citations与references_markdown中才会包含实质性的引用内容——这种正文 编号引用 文末参考列表的形式对 LLM 消费与学术式溯源非常友好。5. 媒体与链接5.1mediaDict[str, List[Dict]]包含发现的图片、视频、音频信息键通常为images、videos、audios。每个条目的常见字段src(str)媒体 URLalt或title(str)描述文本score(float)启发式判定的相关度评分desc或description(Optional[str])从周围文本提取的额外上下文images result.media.get(images, []) for img in images: if img.get(score, 0) 5: print(High-value image:, img[src])5.2linksDict[str, List[Dict]]持有内链与外链数据两个键internal与external。从源码看crawl4ai/utils.py链接提取函数按目标域与当前页面域的关系把锚点分组返回结构正是{internal: [...], external: [...]}。每个条目的常见字段href(str)链接目标text(str)链接文本title(str)title 属性context(str)周围文本片段domain(str)外部链接的目标域名for link in result.links[internal]: print(fInternal link to {link[href]} with text {link[text]})这一字段是深度爬取DeepCrawlStrategy与 URL 种子发现的数据来源之一。6. 附加产物字段6.1extracted_contentOptional[str]若使用了extraction_strategyCSS 选择器、LLM 结构化提取等此处是结构化输出的 JSON 字符串import json if result.extracted_content: data json.loads(result.extracted_content) print(data)6.2downloaded_filesOptional[List[str]]当BrowserConfig中accept_downloadsTrue且配置了downloads_path时列出下载项的本地文件路径if result.downloaded_files: for file_path in result.downloaded_files: print(Downloaded:, file_path)6.3screenshotOptional[str]CrawlerRunConfig中screenshotTrue时的Base64 编码截图import base64 if result.screenshot: with open(page.png, wb) as f: f.write(base64.b64decode(result.screenshot))6.4pdfOptional[bytes]pdfTrue时的原始 PDF 字节流if result.pdf: with open(page.pdf, wb) as f: f.write(result.pdf)6.5mhtmlOptional[str]capture_mhtmlTrue时的 MHTML 快照。MHTMLMIME HTML格式把整页连同 CSS、图片、脚本等资源打包进单个文件适合做离线归档与取证if result.mhtml: with open(page.mhtml, w, encodingutf-8) as f: f.write(result.mhtml)6.6metadataOptional[dict]页面级元数据title、description、OG 数据等if result.metadata: print(Title:, result.metadata.get(title)) print(Author:, result.metadata.get(author))6.7 源码中的扩展字段文档之外的补充从当前仓库源码结构看CrawlResult还带有一批官方参考文档未逐项展开的字段实际使用时同样值得关注tablesList[Dict]表格提取结果形如[{headers, rows, caption, summary}]由table_extraction策略或内置表格发现填充js_execution_resultOptional[Dict]页面内 JS 求值/执行的结果回传head_fingerprint/cached_at/cache_status智能缓存Smart Cache验证元数据cache_status取值为hit、hit_validated、hit_fallback、miss可用于判断结果是否来自缓存及其验证状态crawl_stats反爬重试与代理使用的统计信息配合max_retries/fallback_fetch_function等参数redirected_url与redirected_status_code配对记录重定向最终地址。7.dispatch_result并发任务的资源画像DispatchResult提供并行爬取如arun_many()配合自定义调度器时的并发与资源占用信息源码定义见 crawl4ai/models.pytask_id并行任务的唯一标识memory_usage(float)完成时刻的内存占用MBpeak_memory(float)任务执行期间记录的峰值内存MBstart_time/end_time(datetime)该爬取任务的时间范围error_message(str)调度器或并发相关的错误for result in results: if result.success and result.dispatch_result: dr result.dispatch_result print(fURL: {result.url}, Task ID: {dr.task_id}) print(fMemory: {dr.memory_usage:.1f} MB (Peak: {dr.peak_memory:.1f} MB)) print(fDuration: {dr.end_time - dr.start_time})注意该字段通常在使用arun_many(...)并搭配调度器如MemoryAdaptiveDispatcher或SemaphoreDispatcher实现见 crawl4ai/async_dispatcher.py时才会被填充不使用并发或调度器时保持None。8. 网络请求与控制台消息捕获在CrawlerRunConfig中启用capture_network_requestsTrue与capture_console_messagesTrue后CrawlResult会包含两个诊断字段。捕获逻辑的实现位于 crawl4ai/async_crawler_strategy.py通过监听页面的request/response/requestfailed事件完成。8.1network_requestsOptional[List[Dict[str, Any]]]爬取期间捕获的所有网络请求、响应与失败事件的列表。结构要点每个条目含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: 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(fCaptured {len(requests)} requests, {len(responses)} responses, and {len(failures)} failures) # 分析 API 调用 api_calls [r for r in requests if api in r.get(url, )] # 定位加载失败的资源 for failure in failures: print(fFailed to load: {failure.get(url)} - {failure.get(failure_text)})8.2console_messagesOptional[List[Dict[str, Any]]]爬取期间捕获的所有浏览器控制台消息列表每个条目含type字段log、error、warning等text字段为实际消息文本部分消息含location信息URL、行号、列号所有消息含timestamp字段。if result.console_messages: 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(fMessage type counts: {message_types}) for msg in result.console_messages: if msg.get(type) error: print(fError: {msg.get(text)})这两个字段为页面网络活动与浏览器控制台提供了深度可见性对调试 SPA 数据加载、安全分析以及理解复杂 Web 应用极为有价值。更多细节可参考 网络与控制台捕获文档。9. 完整示例一次性访问所有字段官方文档给出的handle_result是处理CrawlResult的标准模板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(fNetwork requests captured: {len(result.network_requests)}) 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(fResource types: {req_types}) if result.console_messages: print(fConsole messages captured: {len(result.console_messages)}) msg_types {} for msg in result.console_messages: msg_types[msg.get(type, unknown)] msg_types.get(msg.get(type, unknown), 0) 1 print(fMessage types: {msg_types})10. 关键要点、弃用字段与错误处理已弃用的旧属性访问即抛AttributeError源码中这些属性被显式实现为报错并引导迁移的 propertycrawl4ai/models.pymarkdown_v2v0.5 起移除改用result.markdown顶层fit_markdown/fit_html不再是顶层属性改用result.markdown.fit_markdown与result.markdown.fit_html。Fit 内容的生成条件fit_markdown/fit_html只有在MarkdownGenerationStrategy中使用内容过滤器PruningContentFilter、BM25ContentFilter时才出现未用过滤器时保持None。引用与参考文献DefaultMarkdownGenerator启用options{citations: True}后markdown_with_citations与references_markdown才包含实质引用内容便于 LLM 消费或学术式溯源。链接与媒体分组links[internal]/links[external]按域分组media[images]/[videos]/[audios]存储媒体元素可带评分与上下文。错误情况successFalse时查error_message超时、无效 URL 等若失败发生在 HTTP 响应之前status_code可能为None。批量场景arun_many()返回CrawlResultContainercrawl4ai/models.py可迭代地逐个消费CrawlResult每个结果均可独立应用上述所有字段。CrawlResult是 Crawl4AI 爬取产出的统一出口配合合理的BrowserConfig与CrawlerRunConfig一次爬取即可同时产出 HTML、多形态 Markdown、媒体/链接索引、结构化提取 JSON、截图/PDF/MHTML 快照、证书信息与网络诊断数据并全部以结构化字段收敛于此。掌握其字段语义与生成条件是编写可靠数据管道与 AI 输入层的前提。【免费下载链接】crawl4ai Crawl4AI: Open-source LLM Friendly Web Crawler Scraper. Dont be shy, join here: https://discord.gg/jP8KfhDhyN项目地址: https://gitcode.com/GitHub_Trending/craw/crawl4ai创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表