CoolFace
Apppublic

a112961548/playwright-screenshot

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
App README

Playwright HTML 截图服务

基于 FastAPI + Playwright 的 HTML 内容截图 API 服务,支持高清截图、元素截图、多格式输出。

功能特点

  • 🖼️ HTML 内容截图
  • 🎯 CSS 选择器定位特定元素
  • 🔍 高清截图支持 (1x/2x/3x)
  • 📷 支持 PNG/JPEG 格式
  • 🎨 JPEG 质量控制
  • 🚀 快速启动 (FastAPI)
  • ☁️ 免费部署到 Hugging Face Spaces

快速开始

本地运行

bash
# 克隆项目
git clone https://github.com/DuanPeng1314/Playwright-chajian.git
cd Playwright-chajian

# 安装依赖
pip install -r requirements.txt

# 安装 Playwright 浏览器
playwright install chromium

# 启动服务
python -m uvicorn app:app --host 0.0.0.0 --port 7860

Docker 运行

bash
# 构建镜像
docker build -t playwright-screenshot .

# 运行容器
docker run -p 7860:7860 playwright-screenshot

部署到 Hugging Face Spaces

方法一:通过网页界面

  1. 1.登录 Hugging Face
  2. 2.创建新的 Space,选择 Docker SDK
  3. 3.上传以下文件:
  4. 4.Dockerfile
  5. 5.app.py
  6. 6.requirements.txt
  7. 7.README.md (包含 YAML 头部)
  8. 8.等待自动构建完成

方法二:通过 Git 推送

bash
# 创建 Space 后,添加远程仓库
git remote add hf https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME

# 推送代码
git push hf main

API 文档

基础信息

项目说明
服务地址https://your-space.hf.space
API 文档https://your-space.hf.space/docs
交互式文档https://your-space.hf.space/redoc

接口列表

1. 获取服务信息
GET /

响应示例:

json
{
  "message": "Playwright HTML 截图服务",
  "endpoints": {
    "/screenshot": "POST - 提交 HTML 内容进行截图",
    "/screenshot/get": "GET - 通过参数进行截图",
    "/docs": "API 文档"
  },
  "parameters": {
    "width": "视口宽度 (像素), 默认 800",
    "height": "视口高度 (像素), 默认 800",
    "scale": "清晰度/缩放比例, 默认 1.0",
    "format": "图片格式: png 或 jpeg",
    "quality": "JPEG 质量 (1-100)",
    "selector": "CSS 选择器, 截取特定元素"
  }
}
2. POST 截图接口
POST /screenshot

请求体:

json
{
  "html": "<html><body><h1>Hello World</h1></body></html>",
  "selector": null,
  "width": 800,
  "height": 600,
  "scale": 2.0,
  "format": "png",
  "quality": null
}

参数说明:

参数类型必填默认值说明
htmlstring-HTML 内容
selectorstringnullCSS 选择器
widthint800视口宽度 (像素)
heightint800视口高度 (像素)
scalefloat1.0清晰度倍数 (0.5-4.0)
formatstringpng图片格式 (png/jpeg)
qualityintnullJPEG 质量 (1-100)

响应示例:

json
{
  "screenshot": "iVBORw0KGgoAAAANSUhEUg...",
  "success": true,
  "message": "",
  "width": 1600,
  "height": 1200,
  "format": "png"
}
3. GET 截图接口
GET /screenshot/get?html=<html>&width=800&height=600&scale=2.0

使用示例

Python 示例

python
import requests
import base64

# 服务地址
API_URL = "https://your-space.hf.space/screenshot"

# 基础截图
response = requests.post(API_URL, json={
    "html": "<h1>Hello World</h1>",
    "width": 800,
    "height": 600
})

result = response.json()
if result["success"]:
    # 保存截图
    img_data = base64.b64decode(result["screenshot"])
    with open("screenshot.png", "wb") as f:
        f.write(img_data)
    print(f"截图成功: {result['width']}x{result['height']}")

高清截图示例

python
# 2x 高清截图
response = requests.post(API_URL, json={
    "html": "<div style='padding:20px;background:#667eea;color:white;border-radius:10px;'><h1>高清截图</h1></div>",
    "width": 400,
    "height": 300,
    "scale": 2.0  # 输出 800x600
})

# 3x 超清截图
response = requests.post(API_URL, json={
    "html": "<div style='padding:20px;background:#667eea;color:white;border-radius:10px;'><h1>超清截图</h1></div>",
    "width": 400,
    "height": 300,
    "scale": 3.0  # 输出 1200x900
})

元素截图示例

python
html = """
<div class="container">
    <h1>页面标题</h1>
    <div class="card" style="padding:20px;background:#f5f5f5;border-radius:10px;">
        <h2>卡片标题</h2>
        <p>这是卡片内容</p>
    </div>
</div>
"""

# 只截取 .card 元素
response = requests.post(API_URL, json={
    "html": html,
    "selector": ".card",
    "width": 800,
    "height": 600,
    "scale": 2.0
})

JPEG 格式示例

python
# JPEG 格式 + 质量控制
response = requests.post(API_URL, json={
    "html": "<h1>JPEG 截图</h1>",
    "width": 800,
    "height": 600,
    "format": "jpeg",
    "quality": 80  # 质量 80%
})

cURL 示例

bash
# 基础截图
curl -X POST "https://your-space.hf.space/screenshot" \
  -H "Content-Type: application/json" \
  -d '{"html": "<h1>Hello</h1>", "width": 800, "height": 600}'

# 高清截图
curl -X POST "https://your-space.hf.space/screenshot" \
  -H "Content-Type: application/json" \
  -d '{"html": "<h1>Hello</h1>", "width": 400, "height": 300, "scale": 2.0}'

JavaScript 示例

javascript
const API_URL = 'https://your-space.hf.space/screenshot';

async function takeScreenshot(html, options = {}) {
    const response = await fetch(API_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            html: html,
            width: options.width || 800,
            height: options.height || 600,
            scale: options.scale || 1.0,
            selector: options.selector || null,
            format: options.format || 'png'
        })
    });
    
    const result = await response.json();
    
    if (result.success) {
        // 返回 data URL
        return `data:image/${result.format};base64,${result.screenshot}`;
    }
    throw new Error(result.message);
}

// 使用示例
const dataUrl = await takeScreenshot('<h1>Hello World</h1>', { scale: 2.0 });
document.getElementById('img').src = dataUrl;

清晰度说明

scale输入尺寸输出尺寸说明
1.0800x600800x600普通清晰度
2.0800x6001600x1200高清 (2倍)
3.0800x6002400x1800超清 (3倍)
4.0800x6003200x2400极清 (4倍)

常见问题

Q1: 截图返回空白?

检查 HTML 内容是否正确,确保 CSS 样式内联。

Q2: 元素选择器无效?

确保选择器语法正确,元素存在于 HTML 中。

Q3: 服务启动慢?

首次启动需要下载 Chromium 浏览器,约需 1-2 分钟。

Q4: 如何处理中文?

确保 HTML 中包含 <meta charset="UTF-8">


技术栈

  • FastAPI - 高性能 Web 框架
  • Playwright - 浏览器自动化
  • Pydantic - 数据验证
  • Uvicorn - ASGI 服务器

许可证

MIT License


作者

DuanPeng1314

在线演示