Repository navigation
Expand file tree
/
Copy pathscraper_api_client.py
More file actions
141 lines (119 loc) · 6.17 KB
/
Copy pathscraper_api_client.py
File metadata and controls
141 lines (119 loc) · 6.17 KB
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
#!/usr/bin/env python3
"""scraper_api_client.py — the browserless HTTP client for 2Captcha's REST
surface. No site knowledge. `captcha_solver.py` and `fingerprint_client.py`
both sit on top of this rather than calling `requests` directly, so there is
exactly one place that knows the base URL, auth shape and error envelope.
Covers two of 2Captcha's separately-billed products behind one key
(proxies are `proxy_pool.py` + STOCKX_PROXY — a 2captcha.com/
proxy credential, 2prx.com is a synonym for the same product, not a
separate host):
- classic captcha solving (createTask / getTaskResult)
- the Fingerprint API (GET /fingerprint/random)
Never construct a competitor's API call from this module.
"""
from __future__ import annotations
import time
from dataclasses import dataclass
from typing import Optional
import requests
from proxy_pool import redact_credentials
API_BASE = "https://api.2captcha.com"
class TwoCaptchaError(RuntimeError):
pass
class TwoCaptchaAuthError(TwoCaptchaError):
"""Missing/invalid key. Callers treat this as a WARNING, not a crash —
a run continues without solving and reports EXIT_BLOCKED only if the
page turns out to actually need it."""
@dataclass
class CaptchaTask:
task_id: int
class TwoCaptchaClient:
def __init__(self, api_key: Optional[str], timeout: int = 30):
self.api_key = api_key
self.timeout = timeout
def _require_key(self) -> str:
if not self.api_key:
raise TwoCaptchaAuthError(
"TWOCAPTCHA_KEY is not set — get one at https://2captcha.com/setting"
)
return self.api_key
def _post(self, path: str, payload: dict) -> dict:
# A transport failure (DNS, refused connection, timeout) is a solver
# error like any other, not a crash: callers catch TwoCaptchaError
# and carry on. The key travels in the JSON body, not the URL, but
# the text is redacted anyway and the original dropped from the
# chain, so no future URL change can leak one through here.
try:
resp = requests.post(f"{API_BASE}{path}", json=payload, timeout=self.timeout)
except requests.exceptions.RequestException as exc:
raise TwoCaptchaError(f"{path} request failed: {redact_credentials(str(exc))}") from None
try:
data = resp.json()
except ValueError as exc:
raise TwoCaptchaError(f"non-JSON response from {path}: {resp.text[:200]}") from exc
return data
# ----------------------------------------------------------------- #
# Classic captcha solving — createTask / getTaskResult
# ----------------------------------------------------------------- #
def create_task(self, task: dict) -> CaptchaTask:
key = self._require_key()
data = self._post("/createTask", {"clientKey": key, "task": task})
if data.get("errorId"):
raise TwoCaptchaError(f"createTask failed: {data.get('errorCode')} {data.get('errorDescription')}")
return CaptchaTask(task_id=data["taskId"])
def get_task_result(self, task: CaptchaTask) -> dict:
key = self._require_key()
return self._post("/getTaskResult", {"clientKey": key, "taskId": task.task_id})
def get_balance(self) -> float:
"""Account balance in USD, shared across all four 2Captcha products
behind this one key. Cheap way to confirm a key is live without
spending anything (unlike createTask/random_fingerprint, both of
which are billed)."""
key = self._require_key()
data = self._post("/getBalance", {"clientKey": key})
if data.get("errorId"):
raise TwoCaptchaError(f"getBalance failed: {data.get('errorCode')} {data.get('errorDescription')}")
return float(data["balance"])
def solve_and_wait(self, task: dict, poll_interval: float = 5.0, max_wait: float = 180.0) -> str:
"""Blocks (in small polls) until the task resolves, and returns the
solution token. Raises TwoCaptchaError on failure/timeout."""
created = self.create_task(task)
deadline = time.monotonic() + max_wait
while time.monotonic() < deadline:
result = self.get_task_result(created)
if result.get("errorId"):
raise TwoCaptchaError(
f"getTaskResult failed: {result.get('errorCode')} {result.get('errorDescription')}"
)
if result.get("status") == "ready":
solution = result.get("solution", {})
token = solution.get("token") or solution.get("gRecaptchaResponse")
if not token:
raise TwoCaptchaError(f"solved task carried no usable token: {solution!r}")
return token
time.sleep(poll_interval)
raise TwoCaptchaError(f"solve timed out after {max_wait:.0f}s")
# ----------------------------------------------------------------- #
# Fingerprint API
# ----------------------------------------------------------------- #
def random_fingerprint(self, *, tags: Optional[str] = None, country: Optional[str] = None) -> dict:
# Unlike createTask/getTaskResult/getBalance above, this endpoint
# takes its key as a URL query parameter (`?key=...`), not a JSON
# body — and `requests` puts the FULL URL, query string included,
# into the text of every HTTPError and connection error, so the key
# would land in any log that prints the error. Redact before raising, and drop
# the original exception from the chain (`from None`) so its own
# unredacted text can't surface via "the above exception was the
# direct cause of…".
key = self._require_key()
params = {"key": key, "format": "chromium"}
if tags:
params["tags"] = tags
if country:
params["country"] = country
try:
resp = requests.get(f"{API_BASE}/fingerprint/random", params=params, timeout=self.timeout)
resp.raise_for_status()
except requests.exceptions.RequestException as exc:
raise TwoCaptchaError(f"fingerprint/random request failed: {redact_credentials(str(exc))}") from None
return resp.json()