
本文详解 Crawl4ai 中 screenshot=True 参数的正确用法,解决常见报错“got multiple values for keyword argument 'screenshot'”,并提供 PNG 转 JPEG 压缩方案,显著减小截图体积(如从 154MB 降至 4.8MB),兼顾清晰度与实用性。
本文详解 crawl4ai 中 `screenshot=true` 参数的正确用法,解决常见报错“got multiple values for keyword argument 'screenshot'”,并提供 png 转 jpeg 压缩方案,显著减小截图体积(如从 154mb 降至 4.8mb),兼顾清晰度与实用性。
Crawl4ai 的 AsyncWebCrawler.arun() 方法确实支持通过 screenshot=True 获取网页全屏截图,但该功能在较新版本中存在参数签名变更风险:部分版本将 screenshot 同时作为顶层参数和内部处理函数的隐式参数,导致 TypeError: got multiple values for keyword argument 'screenshot'。根本原因并非代码逻辑错误,而是底层方法签名冲突——screenshot 不应再作为 arun() 的显式布尔参数传入。
✅ 正确做法是:移除 screenshot=True,改用 screenshot_options 字典精确控制截图行为(这是当前稳定版推荐方式)。同时,为避免长页面生成超大 PNG(如维基百科页面可达 150MB+),强烈建议在保存前进行有损压缩。
以下是修复后、生产就绪的完整示例:
import asyncio
import os
from base64 import b64decode
from crawl4ai import AsyncWebCrawler, CacheMode
from PIL import Image
import io
async def main():
# 确保输出目录存在
os.makedirs("output", exist_ok=True)
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://en.wikipedia.org/wiki/List_of_common_misconceptions",
cache_mode=CacheMode.BYPASS,
pdf=True,
# ✅ 关键修正:移除 screenshot=True
# ✅ 改用 screenshot_options 控制截图(启用 + 全页)
screenshot_options={"type": "png", "full_page": True}
)
if result.success:
# 处理截图(PNG Base64 → 压缩为 JPEG)
if result.screenshot:
try:
image_data = b64decode(result.screenshot)
image = Image.open(io.BytesIO(image_data))
# 转 RGB(兼容 JPEG)并压缩
compressed = image.convert("RGB")
buffer = io.BytesIO()
compressed.save(buffer, format="JPEG", optimize=True, quality=20)
output_path = "output/wikipedia_screenshot.jpg"
with open(output_path, "wb") as f:
f.write(buffer.getvalue())
print(f"[OK] Screenshot saved to {output_path} (≈4–5 MB)")
except Exception as e:
print(f"[ERROR] Screenshot processing failed: {e}")
# 保存 PDF(保持原样)
if result.pdf:
pdf_path = "output/wikipedia_page.pdf"
with open(pdf_path, "wb") as f:
f.write(result.pdf)
print(f"[OK] PDF saved to {pdf_path}")
print("[SUCCESS] Both PDF and optimized screenshot generated.")
else:
print(f"[ERROR] Crawl failed: {result.error_message}")
if __name__ == "__main__":
asyncio.run(main())
? 关键注意事项:
-
版本兼容性:请确保使用
crawl4ai>=0.3.0;旧版本可能不支持screenshot_options,可执行pip install --upgrade crawl4ai更新。 -
依赖安装:压缩需
Pillow,运行pip install pillow。 -
内存与性能:全页截图(尤其长页面)会占用大量内存,
quality=20是清晰度与体积的平衡点;若文字可读性下降,可尝试quality=30,但文件体积将翻倍。 -
格式选择:
screenshot_options={"type": "jpeg"}在部分环境下可能不生效,因此推荐统一用 PNG 解码 + Pillow 转 JPEG,更可控。
? 进阶提示:如需指定截图区域(如仅可见区域),可改为 screenshot_options={"type": "png", "full_page": False};若需高 DPI 屏幕适配,添加 "scale": "device"(需 Chromium 支持)。
通过以上调整,您将获得稳定、高效、轻量化的网页截图能力,彻底规避参数冲突错误,并实现专业级交付质量。










