Python 中使用 anydoc - firecrawl-anydoc 教程
API 参考Python
anydoc 的 Python 绑定叫 firecrawl-anydoc,转换期间会释放 GIL——这意味着它可以安全地和 asyncio、多线程混用,不会卡住整个进程。
安装
pip install firecrawl-anydoc包自带 Python stubs,类型提示开箱即用。
三个核心 API
import anydoc
# 1. 从路径转
markdown = anydoc.to_markdown("report.docx")
print(markdown)
# 2. 从字节转
data = open("slides.pptx", "rb").read()
md = anydoc.to_markdown_bytes(data)
# 3. 停在文档模型(保留嵌入资源)
doc = anydoc.to_document(data)
# doc 上可访问图片/嵌入对象的原始字节与媒体类型错误处理
try:
anydoc.to_markdown("scanned.pdf")
except anydoc.UnsupportedError as e:
print("不支持的格式或扫描版 PDF:", e)错误以异常子类暴露:UnsupportedError、MalformedError、EncryptedError、ResourceLimitError、MissingPartError、IoError,对应关系见错误处理与限制。
常见场景
asyncio 服务里并发转换
import asyncio
import anydoc
async def convert(path: str) -> str:
return await asyncio.to_thread(anydoc.to_markdown, path)
async def main():
files = ["a.docx", "b.pdf", "c.xlsx"]
results = await asyncio.gather(*(convert(f) for f in files))GIL 在转换期间释放,to_thread 不会互相拖累。
数据分析管道
import anydoc
import pandas as pd
md = anydoc.to_markdown("sales.xlsx")
# 转出来的 Markdown 表格可以直接喂给 LLM 做数据分析批量清洗合同文本
from pathlib import Path
for p in Path("contracts").glob("*.docx"):
md = anydoc.to_markdown(str(p))
Path(f"markdown/{p.stem}.md").write_text(md, encoding="utf-8")小提示
to_markdown_bytes接受bytes,从文件流、HTTP 响应体拿到的字节直接可用- 想保留嵌入资源就停在
to_document,别转字符串 - 大文件转换时留意
ResourceLimit错误——那是安全限制在工作,不是性能问题