Spaces:
Sleeping
Sleeping
File size: 3,095 Bytes
3394804 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# 网站截图服务
这是一个使用 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 |