screenshotapi-to 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- screenshotapi/__init__.py +38 -0
- screenshotapi/client.py +326 -0
- screenshotapi/errors.py +34 -0
- screenshotapi/py.typed +0 -0
- screenshotapi/types.py +53 -0
- screenshotapi_to-1.0.0.dist-info/METADATA +311 -0
- screenshotapi_to-1.0.0.dist-info/RECORD +9 -0
- screenshotapi_to-1.0.0.dist-info/WHEEL +4 -0
- screenshotapi_to-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from .client import ScreenshotAPI
|
|
2
|
+
from .errors import (
|
|
3
|
+
AuthenticationError,
|
|
4
|
+
InsufficientCreditsError,
|
|
5
|
+
InvalidAPIKeyError,
|
|
6
|
+
NetworkError,
|
|
7
|
+
ScreenshotAPIError,
|
|
8
|
+
ScreenshotFailedError,
|
|
9
|
+
)
|
|
10
|
+
from .types import (
|
|
11
|
+
ColorScheme,
|
|
12
|
+
MockupDevice,
|
|
13
|
+
ScreenshotFormat,
|
|
14
|
+
ScreenshotMetadata,
|
|
15
|
+
ScreenshotOptions,
|
|
16
|
+
ScreenshotResult,
|
|
17
|
+
WaitUntil,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__version__ = "1.0.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"__version__",
|
|
24
|
+
"ScreenshotAPI",
|
|
25
|
+
"ScreenshotAPIError",
|
|
26
|
+
"AuthenticationError",
|
|
27
|
+
"InsufficientCreditsError",
|
|
28
|
+
"InvalidAPIKeyError",
|
|
29
|
+
"ScreenshotFailedError",
|
|
30
|
+
"NetworkError",
|
|
31
|
+
"ScreenshotOptions",
|
|
32
|
+
"ScreenshotMetadata",
|
|
33
|
+
"ScreenshotResult",
|
|
34
|
+
"ScreenshotFormat",
|
|
35
|
+
"ColorScheme",
|
|
36
|
+
"WaitUntil",
|
|
37
|
+
"MockupDevice",
|
|
38
|
+
]
|
screenshotapi/client.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping as MappingABC
|
|
4
|
+
from collections.abc import Sequence as SequenceABC
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Dict, Mapping, NoReturn, Optional, Sequence, Union
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from .errors import (
|
|
11
|
+
AuthenticationError,
|
|
12
|
+
InsufficientCreditsError,
|
|
13
|
+
InvalidAPIKeyError,
|
|
14
|
+
NetworkError,
|
|
15
|
+
ScreenshotAPIError,
|
|
16
|
+
ScreenshotFailedError,
|
|
17
|
+
)
|
|
18
|
+
from .types import ScreenshotMetadata, ScreenshotOptions, ScreenshotResult
|
|
19
|
+
|
|
20
|
+
DEFAULT_BASE_URL = "https://screenshotapi.to"
|
|
21
|
+
DEFAULT_TIMEOUT = 60.0
|
|
22
|
+
|
|
23
|
+
ScreenshotOptionsInput = Union[ScreenshotOptions, Mapping[str, object]]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ScreenshotAPI:
|
|
27
|
+
"""Client for the ScreenshotAPI service."""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
api_key: str,
|
|
32
|
+
*,
|
|
33
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
34
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
35
|
+
transport: Optional[httpx.BaseTransport] = None,
|
|
36
|
+
async_transport: Optional[httpx.AsyncBaseTransport] = None,
|
|
37
|
+
) -> None:
|
|
38
|
+
if not api_key:
|
|
39
|
+
raise ValueError("API key is required")
|
|
40
|
+
self._api_key = api_key
|
|
41
|
+
self._base_url = base_url.rstrip("/")
|
|
42
|
+
self._timeout = timeout
|
|
43
|
+
self._transport = transport
|
|
44
|
+
self._async_transport = async_transport
|
|
45
|
+
|
|
46
|
+
def _coerce_options(self, options: ScreenshotOptionsInput) -> ScreenshotOptions:
|
|
47
|
+
if isinstance(options, ScreenshotOptions):
|
|
48
|
+
return options
|
|
49
|
+
|
|
50
|
+
if not isinstance(options, MappingABC):
|
|
51
|
+
raise TypeError("options must be a ScreenshotOptions instance or mapping")
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
return ScreenshotOptions(**dict(options)) # type: ignore[arg-type]
|
|
55
|
+
except TypeError as exc:
|
|
56
|
+
raise ValueError(f"Invalid screenshot options: {exc}") from exc
|
|
57
|
+
|
|
58
|
+
def _validate_options(self, options: ScreenshotOptions) -> None:
|
|
59
|
+
if not options.url and not options.html:
|
|
60
|
+
raise ValueError("Either url or html is required")
|
|
61
|
+
|
|
62
|
+
if (options.geo_latitude is None) != (options.geo_longitude is None):
|
|
63
|
+
raise ValueError("geo_latitude and geo_longitude must be provided together")
|
|
64
|
+
|
|
65
|
+
def _format_query_value(self, value: object) -> str:
|
|
66
|
+
if isinstance(value, bool):
|
|
67
|
+
return str(value).lower()
|
|
68
|
+
if isinstance(value, str):
|
|
69
|
+
return value
|
|
70
|
+
if isinstance(value, SequenceABC):
|
|
71
|
+
return ",".join(str(item) for item in value)
|
|
72
|
+
return str(value)
|
|
73
|
+
|
|
74
|
+
def _set_param(self, params: Dict[str, str], key: str, value: object) -> None:
|
|
75
|
+
if value is not None:
|
|
76
|
+
params[key] = self._format_query_value(value)
|
|
77
|
+
|
|
78
|
+
def _set_body_value(self, body: Dict[str, object], key: str, value: object) -> None:
|
|
79
|
+
if value is not None:
|
|
80
|
+
body[key] = value
|
|
81
|
+
|
|
82
|
+
def _remove_elements_list(
|
|
83
|
+
self, remove_elements: Optional[Sequence[str]]
|
|
84
|
+
) -> Optional[Sequence[str]]:
|
|
85
|
+
if remove_elements is None:
|
|
86
|
+
return None
|
|
87
|
+
if isinstance(remove_elements, str):
|
|
88
|
+
return [
|
|
89
|
+
selector.strip()
|
|
90
|
+
for selector in remove_elements.split(",")
|
|
91
|
+
if selector.strip()
|
|
92
|
+
]
|
|
93
|
+
return list(remove_elements)
|
|
94
|
+
|
|
95
|
+
def _build_params(self, options: ScreenshotOptions) -> Dict[str, str]:
|
|
96
|
+
params: Dict[str, str] = {}
|
|
97
|
+
|
|
98
|
+
self._set_param(params, "url", options.url)
|
|
99
|
+
self._set_param(params, "width", options.width)
|
|
100
|
+
self._set_param(params, "height", options.height)
|
|
101
|
+
self._set_param(params, "fullPage", options.full_page)
|
|
102
|
+
self._set_param(params, "type", options.type)
|
|
103
|
+
self._set_param(params, "quality", options.quality)
|
|
104
|
+
self._set_param(params, "colorScheme", options.color_scheme)
|
|
105
|
+
self._set_param(params, "waitUntil", options.wait_until)
|
|
106
|
+
self._set_param(params, "waitForSelector", options.wait_for_selector)
|
|
107
|
+
self._set_param(params, "delay", options.delay)
|
|
108
|
+
self._set_param(params, "blockAds", options.block_ads)
|
|
109
|
+
self._set_param(params, "removeCookieBanners", options.remove_cookie_banners)
|
|
110
|
+
self._set_param(params, "cssInject", options.css_inject)
|
|
111
|
+
self._set_param(params, "jsInject", options.js_inject)
|
|
112
|
+
self._set_param(params, "stealthMode", options.stealth_mode)
|
|
113
|
+
self._set_param(params, "devicePixelRatio", options.device_pixel_ratio)
|
|
114
|
+
self._set_param(params, "timezone", options.timezone)
|
|
115
|
+
self._set_param(params, "locale", options.locale)
|
|
116
|
+
self._set_param(params, "cacheTtl", options.cache_ttl)
|
|
117
|
+
self._set_param(params, "preloadFonts", options.preload_fonts)
|
|
118
|
+
self._set_param(params, "removeElements", options.remove_elements)
|
|
119
|
+
self._set_param(params, "removePopups", options.remove_popups)
|
|
120
|
+
self._set_param(params, "mockupDevice", options.mockup_device)
|
|
121
|
+
self._set_param(params, "geoLatitude", options.geo_latitude)
|
|
122
|
+
self._set_param(params, "geoLongitude", options.geo_longitude)
|
|
123
|
+
self._set_param(params, "geoAccuracy", options.geo_accuracy)
|
|
124
|
+
return params
|
|
125
|
+
|
|
126
|
+
def _build_body(self, options: ScreenshotOptions) -> Dict[str, object]:
|
|
127
|
+
body: Dict[str, object] = {}
|
|
128
|
+
|
|
129
|
+
self._set_body_value(body, "url", options.url)
|
|
130
|
+
self._set_body_value(body, "html", options.html)
|
|
131
|
+
self._set_body_value(body, "width", options.width)
|
|
132
|
+
self._set_body_value(body, "height", options.height)
|
|
133
|
+
self._set_body_value(body, "fullPage", options.full_page)
|
|
134
|
+
self._set_body_value(body, "type", options.type)
|
|
135
|
+
self._set_body_value(body, "quality", options.quality)
|
|
136
|
+
self._set_body_value(body, "colorScheme", options.color_scheme)
|
|
137
|
+
self._set_body_value(body, "waitUntil", options.wait_until)
|
|
138
|
+
self._set_body_value(body, "waitForSelector", options.wait_for_selector)
|
|
139
|
+
self._set_body_value(body, "delay", options.delay)
|
|
140
|
+
self._set_body_value(body, "blockAds", options.block_ads)
|
|
141
|
+
self._set_body_value(
|
|
142
|
+
body,
|
|
143
|
+
"removeCookieBanners",
|
|
144
|
+
options.remove_cookie_banners,
|
|
145
|
+
)
|
|
146
|
+
self._set_body_value(body, "cssInject", options.css_inject)
|
|
147
|
+
self._set_body_value(body, "jsInject", options.js_inject)
|
|
148
|
+
self._set_body_value(body, "stealthMode", options.stealth_mode)
|
|
149
|
+
self._set_body_value(body, "devicePixelRatio", options.device_pixel_ratio)
|
|
150
|
+
self._set_body_value(body, "timezone", options.timezone)
|
|
151
|
+
self._set_body_value(body, "locale", options.locale)
|
|
152
|
+
self._set_body_value(body, "cacheTtl", options.cache_ttl)
|
|
153
|
+
self._set_body_value(body, "preloadFonts", options.preload_fonts)
|
|
154
|
+
self._set_body_value(
|
|
155
|
+
body,
|
|
156
|
+
"removeElements",
|
|
157
|
+
self._remove_elements_list(options.remove_elements),
|
|
158
|
+
)
|
|
159
|
+
self._set_body_value(body, "removePopups", options.remove_popups)
|
|
160
|
+
self._set_body_value(body, "mockupDevice", options.mockup_device)
|
|
161
|
+
|
|
162
|
+
if options.geo_latitude is not None and options.geo_longitude is not None:
|
|
163
|
+
geo_location: Dict[str, object] = {
|
|
164
|
+
"latitude": options.geo_latitude,
|
|
165
|
+
"longitude": options.geo_longitude,
|
|
166
|
+
}
|
|
167
|
+
self._set_body_value(geo_location, "accuracy", options.geo_accuracy)
|
|
168
|
+
body["geoLocation"] = geo_location
|
|
169
|
+
|
|
170
|
+
return body
|
|
171
|
+
|
|
172
|
+
def _header_int(self, headers: httpx.Headers, key: str) -> int:
|
|
173
|
+
value = headers.get(key)
|
|
174
|
+
if value is None:
|
|
175
|
+
return 0
|
|
176
|
+
try:
|
|
177
|
+
return int(value)
|
|
178
|
+
except ValueError:
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
def _int_from_body(self, value: object) -> int:
|
|
182
|
+
if value is None:
|
|
183
|
+
return 0
|
|
184
|
+
if isinstance(value, bool):
|
|
185
|
+
return int(value)
|
|
186
|
+
if isinstance(value, int):
|
|
187
|
+
return value
|
|
188
|
+
if isinstance(value, str):
|
|
189
|
+
try:
|
|
190
|
+
return int(value)
|
|
191
|
+
except ValueError:
|
|
192
|
+
return 0
|
|
193
|
+
try:
|
|
194
|
+
return int(str(value))
|
|
195
|
+
except (TypeError, ValueError):
|
|
196
|
+
return 0
|
|
197
|
+
|
|
198
|
+
def _parse_metadata(self, headers: httpx.Headers) -> ScreenshotMetadata:
|
|
199
|
+
return ScreenshotMetadata(
|
|
200
|
+
credits_remaining=self._header_int(headers, "x-credits-remaining"),
|
|
201
|
+
screenshot_id=headers.get("x-screenshot-id", ""),
|
|
202
|
+
duration_ms=self._header_int(headers, "x-duration-ms"),
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
def _handle_error(self, response: httpx.Response) -> NoReturn:
|
|
206
|
+
try:
|
|
207
|
+
body = response.json()
|
|
208
|
+
except ValueError:
|
|
209
|
+
raise ScreenshotAPIError(
|
|
210
|
+
f"HTTP {response.status_code}: {response.reason_phrase}",
|
|
211
|
+
response.status_code,
|
|
212
|
+
"unknown_error",
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
if not isinstance(body, MappingABC):
|
|
216
|
+
raise ScreenshotAPIError(
|
|
217
|
+
f"HTTP {response.status_code}: {response.reason_phrase}",
|
|
218
|
+
response.status_code,
|
|
219
|
+
"unknown_error",
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
message = str(body.get("error", body.get("message", "Unknown error")))
|
|
223
|
+
|
|
224
|
+
if response.status_code == 401:
|
|
225
|
+
raise AuthenticationError(message)
|
|
226
|
+
elif response.status_code == 402:
|
|
227
|
+
balance = body.get("balance", body.get("creditBalance", 0))
|
|
228
|
+
raise InsufficientCreditsError(message, self._int_from_body(balance))
|
|
229
|
+
elif response.status_code == 403:
|
|
230
|
+
raise InvalidAPIKeyError(message)
|
|
231
|
+
elif response.status_code == 500:
|
|
232
|
+
raise ScreenshotFailedError(
|
|
233
|
+
str(body.get("message", body.get("error", "Screenshot failed")))
|
|
234
|
+
)
|
|
235
|
+
else:
|
|
236
|
+
raise ScreenshotAPIError(message, response.status_code, "unknown_error")
|
|
237
|
+
|
|
238
|
+
def screenshot(self, options: ScreenshotOptionsInput) -> ScreenshotResult:
|
|
239
|
+
"""Take a screenshot synchronously. Returns image bytes and metadata."""
|
|
240
|
+
coerced = self._coerce_options(options)
|
|
241
|
+
self._validate_options(coerced)
|
|
242
|
+
|
|
243
|
+
try:
|
|
244
|
+
with httpx.Client(
|
|
245
|
+
timeout=self._timeout,
|
|
246
|
+
transport=self._transport,
|
|
247
|
+
) as client:
|
|
248
|
+
if coerced.html is not None:
|
|
249
|
+
response = client.post(
|
|
250
|
+
f"{self._base_url}/api/v1/screenshot",
|
|
251
|
+
json=self._build_body(coerced),
|
|
252
|
+
headers={"x-api-key": self._api_key},
|
|
253
|
+
)
|
|
254
|
+
else:
|
|
255
|
+
response = client.get(
|
|
256
|
+
f"{self._base_url}/api/v1/screenshot",
|
|
257
|
+
params=self._build_params(coerced),
|
|
258
|
+
headers={"x-api-key": self._api_key},
|
|
259
|
+
)
|
|
260
|
+
except httpx.RequestError as exc:
|
|
261
|
+
raise NetworkError(f"Request failed: {exc}") from exc
|
|
262
|
+
|
|
263
|
+
if response.status_code >= 400:
|
|
264
|
+
self._handle_error(response)
|
|
265
|
+
|
|
266
|
+
return ScreenshotResult(
|
|
267
|
+
image=response.content,
|
|
268
|
+
metadata=self._parse_metadata(response.headers),
|
|
269
|
+
content_type=response.headers.get("content-type", "image/png"),
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
async def async_screenshot(
|
|
273
|
+
self, options: ScreenshotOptionsInput
|
|
274
|
+
) -> ScreenshotResult:
|
|
275
|
+
"""Take a screenshot asynchronously. Returns image bytes and metadata."""
|
|
276
|
+
coerced = self._coerce_options(options)
|
|
277
|
+
self._validate_options(coerced)
|
|
278
|
+
|
|
279
|
+
try:
|
|
280
|
+
async with httpx.AsyncClient(
|
|
281
|
+
timeout=self._timeout,
|
|
282
|
+
transport=self._async_transport,
|
|
283
|
+
) as client:
|
|
284
|
+
if coerced.html is not None:
|
|
285
|
+
response = await client.post(
|
|
286
|
+
f"{self._base_url}/api/v1/screenshot",
|
|
287
|
+
json=self._build_body(coerced),
|
|
288
|
+
headers={"x-api-key": self._api_key},
|
|
289
|
+
)
|
|
290
|
+
else:
|
|
291
|
+
response = await client.get(
|
|
292
|
+
f"{self._base_url}/api/v1/screenshot",
|
|
293
|
+
params=self._build_params(coerced),
|
|
294
|
+
headers={"x-api-key": self._api_key},
|
|
295
|
+
)
|
|
296
|
+
except httpx.RequestError as exc:
|
|
297
|
+
raise NetworkError(f"Request failed: {exc}") from exc
|
|
298
|
+
|
|
299
|
+
if response.status_code >= 400:
|
|
300
|
+
self._handle_error(response)
|
|
301
|
+
|
|
302
|
+
return ScreenshotResult(
|
|
303
|
+
image=response.content,
|
|
304
|
+
metadata=self._parse_metadata(response.headers),
|
|
305
|
+
content_type=response.headers.get("content-type", "image/png"),
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
def save(
|
|
309
|
+
self,
|
|
310
|
+
options: ScreenshotOptionsInput,
|
|
311
|
+
path: Union[str, Path],
|
|
312
|
+
) -> ScreenshotMetadata:
|
|
313
|
+
"""Take a screenshot and save it to a file. Returns metadata."""
|
|
314
|
+
result = self.screenshot(options)
|
|
315
|
+
Path(path).write_bytes(result.image)
|
|
316
|
+
return result.metadata
|
|
317
|
+
|
|
318
|
+
async def async_save(
|
|
319
|
+
self,
|
|
320
|
+
options: ScreenshotOptionsInput,
|
|
321
|
+
path: Union[str, Path],
|
|
322
|
+
) -> ScreenshotMetadata:
|
|
323
|
+
"""Take a screenshot asynchronously and save it to a file."""
|
|
324
|
+
result = await self.async_screenshot(options)
|
|
325
|
+
Path(path).write_bytes(result.image)
|
|
326
|
+
return result.metadata
|
screenshotapi/errors.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ScreenshotAPIError(Exception):
|
|
5
|
+
def __init__(self, message: str, status: int, code: str) -> None:
|
|
6
|
+
super().__init__(message)
|
|
7
|
+
self.status = status
|
|
8
|
+
self.code = code
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AuthenticationError(ScreenshotAPIError):
|
|
12
|
+
def __init__(self, message: str) -> None:
|
|
13
|
+
super().__init__(message, 401, "authentication_error")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class InsufficientCreditsError(ScreenshotAPIError):
|
|
17
|
+
def __init__(self, message: str, balance: int) -> None:
|
|
18
|
+
super().__init__(message, 402, "insufficient_credits")
|
|
19
|
+
self.balance = balance
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InvalidAPIKeyError(ScreenshotAPIError):
|
|
23
|
+
def __init__(self, message: str) -> None:
|
|
24
|
+
super().__init__(message, 403, "invalid_api_key")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ScreenshotFailedError(ScreenshotAPIError):
|
|
28
|
+
def __init__(self, message: str) -> None:
|
|
29
|
+
super().__init__(message, 500, "screenshot_failed")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class NetworkError(ScreenshotAPIError):
|
|
33
|
+
def __init__(self, message: str) -> None:
|
|
34
|
+
super().__init__(message, 0, "network_error")
|
screenshotapi/py.typed
ADDED
|
File without changes
|
screenshotapi/types.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Literal, Optional, Sequence
|
|
5
|
+
|
|
6
|
+
ScreenshotFormat = Literal["png", "jpeg", "webp", "pdf"]
|
|
7
|
+
ColorScheme = Literal["light", "dark"]
|
|
8
|
+
WaitUntil = Literal["load", "domcontentloaded", "networkidle0", "networkidle2"]
|
|
9
|
+
MockupDevice = Literal["browser", "iphone", "macbook"]
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class ScreenshotOptions:
|
|
13
|
+
url: Optional[str] = None
|
|
14
|
+
width: Optional[int] = None
|
|
15
|
+
height: Optional[int] = None
|
|
16
|
+
full_page: Optional[bool] = None
|
|
17
|
+
type: Optional[ScreenshotFormat] = None
|
|
18
|
+
quality: Optional[int] = None
|
|
19
|
+
color_scheme: Optional[ColorScheme] = None
|
|
20
|
+
wait_until: Optional[WaitUntil] = None
|
|
21
|
+
wait_for_selector: Optional[str] = None
|
|
22
|
+
delay: Optional[int] = None
|
|
23
|
+
block_ads: Optional[bool] = None
|
|
24
|
+
remove_cookie_banners: Optional[bool] = None
|
|
25
|
+
html: Optional[str] = None
|
|
26
|
+
css_inject: Optional[str] = None
|
|
27
|
+
js_inject: Optional[str] = None
|
|
28
|
+
stealth_mode: Optional[bool] = None
|
|
29
|
+
device_pixel_ratio: Optional[int] = None
|
|
30
|
+
timezone: Optional[str] = None
|
|
31
|
+
locale: Optional[str] = None
|
|
32
|
+
cache_ttl: Optional[int] = None
|
|
33
|
+
preload_fonts: Optional[bool] = None
|
|
34
|
+
remove_elements: Optional[Sequence[str]] = None
|
|
35
|
+
remove_popups: Optional[bool] = None
|
|
36
|
+
mockup_device: Optional[MockupDevice] = None
|
|
37
|
+
geo_latitude: Optional[float] = None
|
|
38
|
+
geo_longitude: Optional[float] = None
|
|
39
|
+
geo_accuracy: Optional[float] = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class ScreenshotMetadata:
|
|
44
|
+
credits_remaining: int
|
|
45
|
+
screenshot_id: str
|
|
46
|
+
duration_ms: int
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class ScreenshotResult:
|
|
51
|
+
image: bytes
|
|
52
|
+
metadata: ScreenshotMetadata
|
|
53
|
+
content_type: str
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: screenshotapi-to
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Python SDK for ScreenshotAPI.
|
|
5
|
+
Project-URL: Homepage, https://screenshotapi.to
|
|
6
|
+
Project-URL: Documentation, https://screenshotapi.to/docs
|
|
7
|
+
Project-URL: Pricing, https://screenshotapi.to/pricing
|
|
8
|
+
Project-URL: Repository, https://github.com/miketromba/screenshotapi-python
|
|
9
|
+
Project-URL: Issues, https://github.com/miketromba/screenshotapi-python/issues
|
|
10
|
+
Project-URL: Support, https://screenshotapi.to
|
|
11
|
+
Author-email: ScreenshotAPI <support@screenshotapi.to>
|
|
12
|
+
Maintainer-email: ScreenshotAPI <support@screenshotapi.to>
|
|
13
|
+
License: MIT License
|
|
14
|
+
|
|
15
|
+
Copyright (c) 2026 ScreenshotAPI
|
|
16
|
+
|
|
17
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
18
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
19
|
+
in the Software without restriction, including without limitation the rights
|
|
20
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
21
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
22
|
+
furnished to do so, subject to the following conditions:
|
|
23
|
+
|
|
24
|
+
The above copyright notice and this permission notice shall be included in all
|
|
25
|
+
copies or substantial portions of the Software.
|
|
26
|
+
|
|
27
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
28
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
29
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
30
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
31
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
32
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
33
|
+
SOFTWARE.
|
|
34
|
+
License-File: LICENSE
|
|
35
|
+
Keywords: api,capture,html-to-image,screenshot,screenshotapi,webpage,website-thumbnail
|
|
36
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
37
|
+
Classifier: Environment :: Web Environment
|
|
38
|
+
Classifier: Intended Audience :: Developers
|
|
39
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
40
|
+
Classifier: Operating System :: OS Independent
|
|
41
|
+
Classifier: Programming Language :: Python :: 3
|
|
42
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
43
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
44
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
45
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
46
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
47
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
48
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
49
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
50
|
+
Classifier: Topic :: Multimedia :: Graphics :: Capture :: Screen Capture
|
|
51
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
52
|
+
Classifier: Typing :: Typed
|
|
53
|
+
Requires-Python: >=3.8
|
|
54
|
+
Requires-Dist: httpx<1.0,>=0.24.0
|
|
55
|
+
Provides-Extra: dev
|
|
56
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
57
|
+
Requires-Dist: mypy<1.15,>=1.8; extra == 'dev'
|
|
58
|
+
Requires-Dist: ruff>=0.8; extra == 'dev'
|
|
59
|
+
Requires-Dist: twine>=5.0; extra == 'dev'
|
|
60
|
+
Provides-Extra: test
|
|
61
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
|
|
62
|
+
Requires-Dist: pytest>=8.0; extra == 'test'
|
|
63
|
+
Description-Content-Type: text/markdown
|
|
64
|
+
|
|
65
|
+
# screenshotapi
|
|
66
|
+
|
|
67
|
+
Official typed Python SDK for
|
|
68
|
+
[ScreenshotAPI](https://screenshotapi.to?utm_source=pypi&utm_medium=python-sdk&utm_campaign=sdk-readme&ref=python-sdk),
|
|
69
|
+
the hosted screenshot API for turning URLs or HTML into PNG, JPEG, WebP, or PDF
|
|
70
|
+
captures.
|
|
71
|
+
|
|
72
|
+
## Install
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install screenshotapi-to
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Python 3.8+ is supported. The distribution package is `screenshotapi-to`, the
|
|
79
|
+
import package is `screenshotapi`, and the package ships `py.typed` metadata for
|
|
80
|
+
type checkers.
|
|
81
|
+
|
|
82
|
+
## Authentication
|
|
83
|
+
|
|
84
|
+
Create an API key in the ScreenshotAPI dashboard, then keep it in an environment
|
|
85
|
+
variable:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
export SCREENSHOTAPI_KEY="sk_live_your_key_here"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
The SDK sends your key in the `x-api-key` header. Keep API keys on the server;
|
|
92
|
+
do not expose them in browser bundles or mobile apps.
|
|
93
|
+
|
|
94
|
+
## First Screenshot
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
import os
|
|
98
|
+
|
|
99
|
+
from screenshotapi import ScreenshotAPI
|
|
100
|
+
|
|
101
|
+
client = ScreenshotAPI(os.environ["SCREENSHOTAPI_KEY"])
|
|
102
|
+
|
|
103
|
+
metadata = client.save(
|
|
104
|
+
{
|
|
105
|
+
"url": "https://example.com",
|
|
106
|
+
"width": 1440,
|
|
107
|
+
"height": 900,
|
|
108
|
+
},
|
|
109
|
+
"screenshot.png",
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
print(f"Screenshot ID: {metadata.screenshot_id}")
|
|
113
|
+
print(f"Credits remaining: {metadata.credits_remaining}")
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Usage
|
|
117
|
+
|
|
118
|
+
### Initialize the Client
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from screenshotapi import ScreenshotAPI
|
|
122
|
+
|
|
123
|
+
client = ScreenshotAPI(
|
|
124
|
+
"sk_live_your_key_here",
|
|
125
|
+
base_url="https://screenshotapi.to",
|
|
126
|
+
timeout=60.0,
|
|
127
|
+
)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Capture Bytes
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from screenshotapi import ScreenshotOptions
|
|
134
|
+
|
|
135
|
+
result = client.screenshot(
|
|
136
|
+
ScreenshotOptions(
|
|
137
|
+
url="https://example.com",
|
|
138
|
+
full_page=True,
|
|
139
|
+
type="webp",
|
|
140
|
+
quality=90,
|
|
141
|
+
color_scheme="dark",
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
image_bytes = result.image
|
|
146
|
+
content_type = result.content_type
|
|
147
|
+
credits_remaining = result.metadata.credits_remaining
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Plain dictionaries are also supported:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
result = client.screenshot(
|
|
154
|
+
{
|
|
155
|
+
"url": "https://example.com",
|
|
156
|
+
"full_page": True,
|
|
157
|
+
"type": "webp",
|
|
158
|
+
}
|
|
159
|
+
)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### Async Capture
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
import asyncio
|
|
166
|
+
import os
|
|
167
|
+
|
|
168
|
+
from screenshotapi import ScreenshotAPI
|
|
169
|
+
|
|
170
|
+
client = ScreenshotAPI(os.environ["SCREENSHOTAPI_KEY"])
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
async def main() -> None:
|
|
174
|
+
result = await client.async_screenshot({"url": "https://example.com"})
|
|
175
|
+
print(f"Duration: {result.metadata.duration_ms}ms")
|
|
176
|
+
|
|
177
|
+
await client.async_save({"url": "https://example.com"}, "screenshot.png")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
asyncio.run(main())
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## Advanced Options
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
result = client.screenshot(
|
|
187
|
+
{
|
|
188
|
+
"url": "https://example.com/dashboard",
|
|
189
|
+
"width": 1280,
|
|
190
|
+
"height": 720,
|
|
191
|
+
"device_pixel_ratio": 2,
|
|
192
|
+
"full_page": False,
|
|
193
|
+
"type": "webp",
|
|
194
|
+
"quality": 85,
|
|
195
|
+
"color_scheme": "dark",
|
|
196
|
+
"wait_until": "networkidle0",
|
|
197
|
+
"wait_for_selector": ".ready",
|
|
198
|
+
"delay": 500,
|
|
199
|
+
"block_ads": True,
|
|
200
|
+
"remove_cookie_banners": True,
|
|
201
|
+
"remove_popups": True,
|
|
202
|
+
"remove_elements": [".newsletter", "#cookie-banner"],
|
|
203
|
+
"css_inject": "body { caret-color: transparent; }",
|
|
204
|
+
"js_inject": "window.scrollTo(0, 0)",
|
|
205
|
+
"stealth_mode": True,
|
|
206
|
+
"timezone": "America/New_York",
|
|
207
|
+
"locale": "en-US",
|
|
208
|
+
"cache_ttl": 3600,
|
|
209
|
+
"preload_fonts": True,
|
|
210
|
+
"geo_latitude": 40.7128,
|
|
211
|
+
"geo_longitude": -74.0060,
|
|
212
|
+
"geo_accuracy": 25,
|
|
213
|
+
}
|
|
214
|
+
)
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
HTML rendering uses `POST /api/v1/screenshot` automatically:
|
|
218
|
+
|
|
219
|
+
```python
|
|
220
|
+
result = client.screenshot(
|
|
221
|
+
{
|
|
222
|
+
"html": "<html><body><h1>Invoice #123</h1></body></html>",
|
|
223
|
+
"type": "pdf",
|
|
224
|
+
}
|
|
225
|
+
)
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
Supported options:
|
|
229
|
+
|
|
230
|
+
| Python option | API parameter | Notes |
|
|
231
|
+
|---|---|---|
|
|
232
|
+
| `url` | `url` | Required unless `html` is provided |
|
|
233
|
+
| `html` | `html` | Raw HTML, sent with POST |
|
|
234
|
+
| `width`, `height` | `width`, `height` | Viewport size |
|
|
235
|
+
| `full_page` | `fullPage` | Capture full scrollable page |
|
|
236
|
+
| `type` | `type` | `png`, `jpeg`, `webp`, or `pdf` |
|
|
237
|
+
| `quality` | `quality` | JPEG/WebP quality, 1-100 |
|
|
238
|
+
| `color_scheme` | `colorScheme` | `light` or `dark` |
|
|
239
|
+
| `wait_until` | `waitUntil` | `load`, `domcontentloaded`, `networkidle0`, `networkidle2` |
|
|
240
|
+
| `wait_for_selector` | `waitForSelector` | CSS selector to wait for |
|
|
241
|
+
| `delay` | `delay` | Extra delay in milliseconds |
|
|
242
|
+
| `block_ads` | `blockAds` | Remove ads before capture |
|
|
243
|
+
| `remove_cookie_banners` | `removeCookieBanners` | Remove common consent banners |
|
|
244
|
+
| `css_inject`, `js_inject` | `cssInject`, `jsInject` | Inject CSS or JavaScript before capture |
|
|
245
|
+
| `stealth_mode` | `stealthMode` | Enable anti-bot fingerprint masking |
|
|
246
|
+
| `device_pixel_ratio` | `devicePixelRatio` | `1`, `2`, or `3` |
|
|
247
|
+
| `timezone`, `locale` | `timezone`, `locale` | Browser emulation settings |
|
|
248
|
+
| `cache_ttl` | `cacheTtl` | Cache identical captures for N seconds |
|
|
249
|
+
| `preload_fonts` | `preloadFonts` | Preload Google Fonts before capture |
|
|
250
|
+
| `remove_elements` | `removeElements` | CSS selectors to remove |
|
|
251
|
+
| `remove_popups` | `removePopups` | Remove common overlays and modals |
|
|
252
|
+
| `mockup_device` | `mockupDevice` | `browser`, `iphone`, or `macbook` frame |
|
|
253
|
+
| `geo_latitude`, `geo_longitude`, `geo_accuracy` | `geoLocation` or geo query params | Browser geolocation override |
|
|
254
|
+
|
|
255
|
+
## Error Handling
|
|
256
|
+
|
|
257
|
+
```python
|
|
258
|
+
from screenshotapi import (
|
|
259
|
+
AuthenticationError,
|
|
260
|
+
InsufficientCreditsError,
|
|
261
|
+
InvalidAPIKeyError,
|
|
262
|
+
NetworkError,
|
|
263
|
+
ScreenshotAPI,
|
|
264
|
+
ScreenshotAPIError,
|
|
265
|
+
ScreenshotFailedError,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
client = ScreenshotAPI("sk_live_your_key_here")
|
|
269
|
+
|
|
270
|
+
try:
|
|
271
|
+
client.screenshot({"url": "https://example.com"})
|
|
272
|
+
except AuthenticationError:
|
|
273
|
+
print("Missing API key")
|
|
274
|
+
except InvalidAPIKeyError:
|
|
275
|
+
print("Invalid or revoked API key")
|
|
276
|
+
except InsufficientCreditsError as exc:
|
|
277
|
+
print(f"No credits remaining. Balance: {exc.balance}")
|
|
278
|
+
except ScreenshotFailedError as exc:
|
|
279
|
+
print(f"Screenshot failed: {exc}")
|
|
280
|
+
except NetworkError as exc:
|
|
281
|
+
print(f"Could not reach ScreenshotAPI: {exc}")
|
|
282
|
+
except ScreenshotAPIError as exc:
|
|
283
|
+
print(f"ScreenshotAPI error {exc.status} ({exc.code}): {exc}")
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
## Examples
|
|
287
|
+
|
|
288
|
+
Runnable examples live in `examples/`:
|
|
289
|
+
|
|
290
|
+
- `script_usage.py` for one-off scripts and cron jobs
|
|
291
|
+
- `fastapi_app.py` for FastAPI endpoints
|
|
292
|
+
- `django_view.py` for Django views
|
|
293
|
+
- `flask_app.py` for Flask routes
|
|
294
|
+
|
|
295
|
+
## Pricing and Free Tier
|
|
296
|
+
|
|
297
|
+
ScreenshotAPI includes
|
|
298
|
+
[200 free screenshots per month](https://screenshotapi.to/pricing?utm_source=pypi&utm_medium=python-sdk&utm_campaign=sdk-readme&ref=python-sdk)
|
|
299
|
+
with no credit card required. Paid subscriptions and credit packs are available
|
|
300
|
+
when you need more volume.
|
|
301
|
+
|
|
302
|
+
## Links
|
|
303
|
+
|
|
304
|
+
- [Documentation](https://screenshotapi.to/docs?utm_source=pypi&utm_medium=python-sdk&utm_campaign=sdk-readme&ref=python-sdk)
|
|
305
|
+
- [Screenshot API reference](https://screenshotapi.to/docs/api/screenshot?utm_source=pypi&utm_medium=python-sdk&utm_campaign=sdk-readme&ref=python-sdk)
|
|
306
|
+
- [Pricing](https://screenshotapi.to/pricing?utm_source=pypi&utm_medium=python-sdk&utm_campaign=sdk-readme&ref=python-sdk)
|
|
307
|
+
- [Support](mailto:support@screenshotapi.to?subject=Python%20SDK%20support)
|
|
308
|
+
|
|
309
|
+
## License
|
|
310
|
+
|
|
311
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
screenshotapi/__init__.py,sha256=kOQCcuSuzokMuG8gkKX0_Rgfd9aiPhP35qG-HpaFggU,763
|
|
2
|
+
screenshotapi/client.py,sha256=cPMA52l7mJvwM5R92lgYyK8ogdhRl3aZDslLE1nNVHw,13135
|
|
3
|
+
screenshotapi/errors.py,sha256=SZ3j657JzN-VBS0BzK22J-RQzBfP9xTFZBpkzn9ULBo,1049
|
|
4
|
+
screenshotapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
screenshotapi/types.py,sha256=5SovilgY7QJjN4SjW0gYJR4Wb0iB-Qwp3rvtLqaAEg0,1667
|
|
6
|
+
screenshotapi_to-1.0.0.dist-info/METADATA,sha256=Aw3aBCJNEMWgznzLaczcP0Y-56Odk7dzS7KdvOmeC44,10183
|
|
7
|
+
screenshotapi_to-1.0.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
8
|
+
screenshotapi_to-1.0.0.dist-info/licenses/LICENSE,sha256=Tl6YDdBdkKGtgT2UyDDDvrxAcZw2PEhy6GvuMzhtlvU,1070
|
|
9
|
+
screenshotapi_to-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ScreenshotAPI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|