ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

如何用 Crawl4AI 把本地 HTML 文件和原始 HTML 字符串转成 Markdown

如何用 Crawl4AI 把本地 HTML 文件和原始 HTML 字符串转成 Markdown 如何用 Crawl4AI 把本地 HTML 文件和原始 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如果你手上已经有一份网页的 HTML保存在本地文件里或者以字符串形式存在于内存中想直接得到对应的 Markdown 文本而不需要再发起一次网络请求Crawl4AI 的AsyncWebCrawler可以通过url参数的前缀来完成这件事本地文件用file://前缀原始 HTML 字符串用raw:前缀。转换结果通过result.markdown获取。前提是通过 pip 安装了 Crawl4AI 及其浏览器依赖。准备条件安装 Crawl4AI按照 安装文档基础安装只需要两条命令pip install crawl4ai playwright install # Install Playwright dependencies如果 Playwright 安装遇到依赖问题文档主要提到 Ubuntu 场景文档给出了对应的apt-get依赖列表可按 installation.md 中的说明补装。安装完成后可按文档提供的最小脚本验证import asyncio from crawl4ai import AsyncWebCrawler async def main(): async with AsyncWebCrawler(verboseTrue) as crawler: result await crawler.arun(urlhttps://www.example.com) print(result.markdown[:500]) # Print first 500 characters if __name__ __main__: asyncio.run(main())能打印出 example.com 的前 500 个字符说明环境可用。用file://前缀解析本地 HTML 文件把文件绝对路径加上file://前缀作为url传入即可无需网络请求。示例来自 local-files.mdimport asyncio from crawl4ai import AsyncWebCrawler, CacheMode, CrawlerRunConfig async def crawl_local_file(): local_file_path /path/to/apple.html # Replace with your file path file_url ffile://{local_file_path} config CrawlerRunConfig(cache_modeCacheMode.BYPASS) async with AsyncWebCrawler() as crawler: result await crawler.arun(urlfile_url, configconfig) if result.success: print(Markdown Content from Local File:) print(result.markdown) else: print(fFailed to crawl local file: {result.error_message}) asyncio.run(crawl_local_file())其中/path/to/apple.html是文档中给定的示例路径运行前必须替换成你自己的本地 HTML 文件的绝对路径。CacheMode.BYPASS用于绕过缓存读取保证拿到新鲜内容。判断成功与否看result.success转换后的 Markdown 在result.markdown失败原因在result.error_message。用raw:前缀解析原始 HTML 字符串HTML 字符串直接加raw:前缀拼进url参数import asyncio from crawl4ai import AsyncWebCrawler, CacheMode from crawl4ai.async_configs import CrawlerRunConfig async def crawl_raw_html(): raw_html htmlbodyh1Hello, World!/h1/body/html raw_html_url fraw:{raw_html} config CrawlerRunConfig(cache_modeCacheMode.BYPASS) async with AsyncWebCrawler() as crawler: result await crawler.arun(urlraw_html_url, configconfig) if result.success: print(Markdown Content from Raw HTML:) print(result.markdown) else: print(fFailed to crawl raw HTML: {result.error_message}) asyncio.run(crawl_raw_html())raw://双斜杠写法同样有效quickstart.md 中就用urlraw:// raw_html传递 HTML 内容并明确说明这种方式不发起网络请求两种写法对应源码 async_crawler_strategy.py 中对raw://与raw:两种前缀的剥离逻辑。如果你的 HTML 片段来自某个网页、包含相对链接可以在CrawlerRunConfig中传base_url用于 Markdown 中的链接解析这在 v0.8.0 发布说明 中有示例config CrawlerRunConfig(base_urlhttps://example.com) result await crawler.arun(urlraw:{html}, configconfig)base_url是可选参数不传时按 async_configs.py 中的说明不会回退到原始 HTML 字符串本身。验证转换结果与 Web 抓取一致local-files.md 提供了一个完整的对照脚本可以验证三条路径Web 抓取、本地文件、raw HTML产出的 Markdown 是否一致。该脚本以 Wikipedia 的 Apple 页面为例依次做三件事抓取https://en.wikipedia.org/wiki/apple把result.html写到脚本同目录的apple.html用file://前缀重新解析该文件断言 Markdown 长度与第一步一致读取文件内容作为raw:输入再解析一次再次断言长度一致。import os import sys import asyncio from pathlib import Path from crawl4ai import AsyncWebCrawler, CacheMode, CrawlerRunConfig async def main(): wikipedia_url https://en.wikipedia.org/wiki/apple script_dir Path(__file__).parent html_file_path script_dir / apple.html async with AsyncWebCrawler() as crawler: # Step 1: Crawl the Web URL print(\n Step 1: Crawling the Wikipedia URL ) web_config CrawlerRunConfig(cache_modeCacheMode.BYPASS) result await crawler.arun(urlwikipedia_url, configweb_config) if not result.success: print(fFailed to crawl {wikipedia_url}: {result.error_message}) return with open(html_file_path, w, encodingutf-8) as f: f.write(result.html) web_crawl_length len(result.markdown) print(fLength of markdown from web crawl: {web_crawl_length}\n) # Step 2: Crawl from the Local HTML File print( Step 2: Crawling from the Local HTML File ) file_url ffile://{html_file_path.resolve()} file_config CrawlerRunConfig(cache_modeCacheMode.BYPASS) local_result await crawler.arun(urlfile_url, configfile_config) if not local_result.success: print(fFailed to crawl local file {file_url}: {local_result.error_message}) return local_crawl_length len(local_result.markdown) assert web_crawl_length local_crawl_length, Markdown length mismatch print(✅ Markdown length matches between web and local file crawl.\n) # Step 3: Crawl Using Raw HTML Content print( Step 3: Crawling Using Raw HTML Content ) with open(html_file_path, r, encodingutf-8) as f: raw_html_content f.read() raw_html_url fraw:{raw_html_content} raw_config CrawlerRunConfig(cache_modeCacheMode.BYPASS) raw_result await crawler.arun(urlraw_html_url, configraw_config) if not raw_result.success: print(fFailed to crawl raw HTML content: {raw_result.error_message}) return raw_crawl_length len(raw_result.markdown) assert web_crawl_length raw_crawl_length, Markdown length mismatch print(✅ Markdown length matches between web and raw HTML crawl.\n) print(All tests passed successfully!) if html_file_path.exists(): os.remove(html_file_path) if __name__ __main__: asyncio.run(main())运行前注意这个脚本的两个副作用它会在脚本所在目录写入临时文件apple.html并在结尾自动删除它os.remove。另外第一步需要能访问 Wikipedia 的网络环境这一步只用于产生对照样本如果你只想测试本地文件到 Markdown 的转换直接用上一节的file://示例即可不需要跑完整脚本。脚本的验证逻辑是长度断言两次断言都通过、打印All tests passed successfully!说明本地文件和 raw HTML 两种输入得到的 Markdown 与 Web 抓取结果一致。若长度不一致脚本会以Markdown length mismatch失败退出。理解 raw:/file:// 的执行方式快路径与浏览器处理默认情况下raw:和file://URL 走快路径直接拿到 HTML 返回不做浏览器交互。这在 async_configs.py 的process_in_browser参数说明中写得很明确process_in_browser默认Falseraw:/file://URL 走快路径不经过浏览器设为True可强制走浏览器管线从而支持js_code、wait_for、滚动等能力当检测到需要浏览器的参数如js_code、wait_for、screenshot、pdf等时会自动启用浏览器处理。也就是说如果你的 HTML 里有需要 JavaScript 才能呈现的内容或者需要截图/PDF 输出要么显式设置process_in_browserTrue要么直接带上对应的浏览器参数如screenshot、pdf触发自动启用。v0.8.0 发布说明 列出了该版本新增的raw:/file://支持项包括 PDF、MHTML 生成和截图说明这些输出能力对本地输入同样适用。限制与失败排查url参数必须是四种前缀之一。源码 async_crawler_strategy.py 中对不合法的输入直接报错URL must start with http://, https://, file://, or raw:。遇到这条错误检查前缀拼写。本地输入路径必须是绝对路径file://前缀后直接跟路径文档示例中file_url ffile://{local_file_path}。快路径下不会执行页面 JavaScript依赖动态渲染的 HTML 片段得不到渲染结果如需渲染按上一节启用浏览器处理。失败时不要只看退出码result.success为False时打印result.error_message获取具体原因这是文档示例代码统一使用的判断方式。完成本地文件或 HTML 字符串到 Markdown 的转换后如果需要进一步控制输出如链接引用、换行宽度、内容过滤可继续阅读 Markdown Generation 文档 中关于DefaultMarkdownGenerator的options与 content filter 的说明。【免费下载链接】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),仅供参考
返回列表