Spaces:
Sleeping
Sleeping
| # 网站截图服务 | |
| 这是一个使用 FastAPI 和 Playwright 构建的简单网站截图服务,可以生成任何网页的高质量截图。 | |
| ## 功能特点 | |
| - 支持任何公开可访问的网页截图 | |
| - 可自定义截图尺寸 | |
| - 支持 PNG 格式输出 | |
| - 自动缓存生成的截图 | |
| - 提供 REST API 接口 | |
| - 异步处理,高性能 | |
| ## 系统要求 | |
| - Python 3.9 或更高版本 | |
| - pip 包管理器 | |
| ## 安装步骤 | |
| 1. 克隆或下载本项目 | |
| 2. 安装依赖 | |
| ```bash | |
| pip install -r requirements.txt | |
| playwright install chromium | |
| ``` | |
| 3. 启动服务 | |
| ```bash | |
| python screenshot_service.py | |
| ``` | |
| 服务将在 `http://localhost:7860` 启动。 | |
| ## API 使用说明 | |
| ### 生成网页截图 | |
| **请求**: | |
| ``` | |
| POST /capture | |
| Content-Type: application/json | |
| ``` | |
| **请求体**: | |
| ```json | |
| { | |
| "url": "https://example.com", | |
| "width": 1024, | |
| "height": 768, | |
| "format": "png", | |
| "custom_headers": { | |
| "User-Agent": "Custom User Agent" | |
| } | |
| } | |
| ``` | |
| 参数说明: | |
| - `url`: 必填,要截图的网页地址 | |
| - `width`: 可选,截图宽度,默认 1024 | |
| - `height`: 可选,截图高度,默认 768 | |
| - `format`: 可选,图片格式,目前支持 png,默认为 png | |
| - `custom_headers`: 可选,自定义请求头 | |
| **成功响应**: | |
| ```json | |
| { | |
| "success": true, | |
| "imageUrl": "http://localhost:7860/screenshots/example_com_1633456789.png", | |
| "filename": "example_com_1633456789.png" | |
| } | |
| ``` | |
| **错误响应**: | |
| ```json | |
| { | |
| "detail": "截图生成失败: 导航超时,网页加载时间过长" | |
| } | |
| ``` | |
| ### 检查服务健康状态 | |
| **请求**: | |
| ``` | |
| GET /health | |
| ``` | |
| **响应**: | |
| ```json | |
| { | |
| "status": "ok" | |
| } | |
| ``` | |
| ## 在你的应用中使用 | |
| 在客户端 JavaScript 中调用服务: | |
| ```javascript | |
| async function getScreenshot(url) { | |
| try { | |
| const response = await fetch('http://localhost:7860/capture', { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify({ | |
| url: url, | |
| width: 1024, | |
| height: 768 | |
| }) | |
| }); | |
| const data = await response.json(); | |
| return data.imageUrl; | |
| } catch (error) { | |
| console.error('截图服务请求失败:', error); | |
| return null; | |
| } | |
| } | |
| ``` | |
| 在 Python 中调用服务: | |
| ```python | |
| import requests | |
| def get_screenshot(url): | |
| try: | |
| response = requests.post( | |
| 'http://localhost:7860/capture', | |
| json={ | |
| 'url': url, | |
| 'width': 1024, | |
| 'height': 768 | |
| } | |
| ) | |
| data = response.json() | |
| return data['imageUrl'] | |
| except Exception as e: | |
| print(f'截图服务请求失败: {str(e)}') | |
| return None | |
| ``` | |
| ## 部署建议 | |
| 在生产环境部署时,建议: | |
| 1. 使用 Docker 容器化部署 | |
| 2. 使用 Gunicorn 或 Uvicorn 作为生产级 ASGI 服务器 | |
| 3. 设置合适的超时时间和内存限制 | |
| 4. 配置 HTTPS 以保证安全性 | |
| 5. 添加访问限制或身份验证 | |
| ## Docker 部署 | |
| 1. 构建镜像 | |
| ```bash | |
| docker build -t screenshot-service . | |
| ``` | |
| 2. 运行容器 | |
| ```bash | |
| docker run -p 7860:7860 screenshot-service | |
| ``` | |
| ## 许可证 | |
| MIT |