Repository navigation
Expand file tree
/
Copy pathscraper_api_client.py
More file actions
398 lines (350 loc) · 17.6 KB
/
Copy pathscraper_api_client.py
File metadata and controls
398 lines (350 loc) · 17.6 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
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env python3
"""
binance-scraper — 2captcha Scraper API edition (fourth engine)
==============================================================
A fourth way to run this scraper. Unlike the three browser engines, this one
manages **no browser and no CDP session of its own**: it POSTs a URL to
2captcha's separate **Scraper API** (https://scraper.2captcha.com, a
different product from the Scraping Browser API the other three reach
through --cdp-endpoint), gets the response back over plain HTTPS, and feeds
it to this project's product_parser.
Why you would want it: no Chromium to install, runs from a tiny container or
a lambda.
WHAT THIS SITE NEEDS — READ THIS FIRST
--------------------------------------
This client reads **`--mode announcements`** only. The Scraper API fetches a
URL, and the announcements list is a GET endpoint with a URL. The P2P and
copy-trading endpoints answer POST only, and this client does not implement
a POST through the Scraper API: `--mode p2p` and `--mode copytrading` are
refused with that reason rather than attempted. Use a browser engine for
them.
It is also not a path you NEED. All three endpoints answered a plain HTTPS
request from a datacentre address with no key (measured 2026-09-24), so
this client is for a setup that has no local browser, not for getting past
anything.
Usage
-----
python3 scraper_api_client.py --category delisting --pages 2
# the key comes from $TWOCAPTCHA_KEY and a CDP endpoint from
# $BINANCE_CDP_ENDPOINT, so neither needs to be typed — a secret in
# argv is readable by anything that can run `ps`
Requires: pip install -r requirements.txt
(no playwright/selenium/pyppeteer needed for this engine)
"""
import argparse
import json
import logging
import os
import re
import sys
import time
from typing import Optional
import requests
import html as html_lib
from product_parser import (ANN_CATALOGS, DEFAULT_ANN_CATALOG, Query,
api_error, catalog_id, detect_page_state,
pages_available, pages_to_fetch, parse_page,
request_for, total_results)
from output_writer import dedupe_by_key, finish_run, SOURCE_DEFAULT
import env_config
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger("scraper_api_client")
API_BASE = "https://scraper.2captcha.com"
SYNC_ENDPOINT = f"{API_BASE}/tasks/sync"
# The API caps `timeout` at 120s and rejects bodies over 10,000 bytes.
MAX_API_TIMEOUT = 120
# Exit codes. Kept distinct from 2 (bad usage) on purpose: a remote API
# failing is not the operator passing wrong arguments, and a harness that
# lumps them together sends you looking in the wrong place. An early run
# reported `exit=2` for an HTTP 422 from the API — which reads as "you called
# it wrong".
#
# Imported rather than redefined: the browser engines return the same code for
# a Scraping Browser that will not accept a connection, and two definitions
# of one exit code is how a family's contract drifts.
from output_writer import EXIT_API_ERROR # noqa: E402
def _mask_credentials(url: str) -> str:
"""Never print a username:password embedded in a ws://... or http://... URL."""
if "@" not in url:
return url
scheme_sep = url.find("://")
if scheme_sep == -1:
return url
scheme, rest = url[:scheme_sep + 3], url[scheme_sep + 3:]
_, _, host_part = rest.partition("@")
return f"{scheme}***:***@{host_part}"
# Credentials embedded ANYWHERE in a blob of text, not just in a string that
# is entirely a URL — and every occurrence, not the first. A masker that
# handles one occurrence prints the password the other four times and looks
# like it is working.
_CREDS_IN_TEXT_RE = re.compile(r"([a-z][a-z0-9+.-]*://)[^/\s'\"@]+@", re.IGNORECASE)
# Same shape as captcha_solver's and fingerprint_client's. A third copy is
# one too many and they should be unified in a family pass; reaching into
# another module's private name to avoid it would be worse.
_KEY_IN_TEXT_RE = re.compile(
r"((?:client)?key|token|api[_-]?key)=([^&\s'\"]{6,})", re.IGNORECASE)
def _redact_debug_header(value: str) -> str:
"""The x-debug header, safe to log.
SECURITY.md names this header as one of three places credentials reach a
log unmasked, and it was logged verbatim: the API echoes back the task it
ran, so a run driven through a credentialed CDP endpoint put that
endpoint's username and password into the log, and a key passed as a
query parameter would go the same way.
Redaction rather than an allowlist of fields, deliberately: the header is
the API's own metadata and its shape is not ours to pin, so an allowlist
would silently drop the cost and timing figures this is logged FOR the
first time the API adds a field.
"""
return _KEY_IN_TEXT_RE.sub(r"\1=***",
_CREDS_IN_TEXT_RE.sub(r"\1***:***@", value))
def _build_wait_for(args) -> Optional[dict]:
"""`waitFor` is an OBJECT. Measured 2026-09-23 against the live
/tasks/sync endpoint: the JSON-encoded string form this client used to
send was answered with HTTP 422 ("params.waitFor must be an object")
and was still billed ($0.0005); the same request with an object
answered HTTP 200. The earlier note here, that the API wanted a
double-encoded string, no longer describes the API.
Default (no flag): wait for the DOM. On a challenge-protected page
that resolves instantly against the challenge page itself — which is
exactly the trap documented in this module's docstring, so
--wait-text/--wait-element exist to wait on something only the real
page can contain."""
if args.wait_text:
return {"text": args.wait_text}
if args.wait_element:
return {"element": args.wait_element, "checkVisible": True}
if args.wait_state:
return {"state": args.wait_state}
return None
def fetch_html(args) -> str:
payload = {
"task_type": "scrape",
"url": args.url,
"data_format": "raw", # we want HTML; product_parser does the rest
"format": "json", # {"status": verdict, "http_code": target status, "headers", "body"}
"timeout": min(args.timeout, MAX_API_TIMEOUT),
}
wait_for = _build_wait_for(args)
if wait_for:
payload["waitFor"] = wait_for
logger.info("waitFor: %s", json.dumps(wait_for))
if args.cdp_url:
payload["cdpurl"] = args.cdp_url
logger.info("Routing through an existing browser session: %s",
_mask_credentials(args.cdp_url))
logger.info("POST %s (url=%s)", SYNC_ENDPOINT, args.url)
resp = requests.post(
SYNC_ENDPOINT,
headers={"Authorization": f"Bearer {args.key}", "Content-Type": "application/json"},
json=payload,
# Give the HTTP call more headroom than the API-side task timeout,
# otherwise a task that legitimately runs the full 120s looks like
# a client-side network failure.
timeout=min(args.timeout, MAX_API_TIMEOUT) + 30,
)
# The API returns its own per-task metadata (price, timings, status)
# in an x-debug header — worth logging, it's the only place the real
# cost of the call shows up.
debug = resp.headers.get("x-debug")
if debug:
logger.info("x-debug: %s", _redact_debug_header(debug))
if resp.status_code != 200:
# 422 = task ran but errored (this is what a bad/unreachable
# cdpurl produces: "CDP connect failed (user cdpurl) after N
# attempts"); 402 = out of balance; 408 = sync wait exceeded.
raise RuntimeError(
f"Scraper API returned HTTP {resp.status_code}: {resp.text[:500]}"
)
body = resp.json()
html = body.get("body") or ""
# The TARGET's HTTP status is `http_code`. `status` is the API's own
# verdict string ("success"), measured 2026-09-23 -- passing it on
# handed the page classifier a string, so a target 403/503 was never
# seen. Fall back to `status` only if it is itself an integer.
upstream_status = body.get("http_code")
if not isinstance(upstream_status, int):
legacy = body.get("status")
upstream_status = legacy if isinstance(legacy, int) and not isinstance(legacy, bool) else None
logger.info("Upstream page HTTP status %s, %d bytes of HTML.", upstream_status, len(html))
# The STATUS is returned alongside the HTML, not thrown away. It used to
# be, and that cost this engine the family's central distinction. On this
# site a refusal carries no markup at all — nothing a challenge check
# on it, so the challenge check below finds nothing and the run fell
# through to "0 products" and exit 4. A pipeline branching on the exit
# code then reads a block as an empty category. See detect_page_state,
# which the three browser engines already reach through page_flow.
return html, upstream_status
_PRE_RE = re.compile(r"<pre[^>]*>(.*?)</pre>", re.S | re.I)
def json_text(body: str) -> str:
"""The endpoint's JSON out of what the Scraper API returned.
The API loads the URL in a browser, and a browser shows a JSON response
inside its own viewer markup, so the body may be HTML with the payload
in a <pre>. Returned unchanged when it already is JSON.
"""
s = (body or "").strip()
if s.startswith("{"):
return s
m = _PRE_RE.search(s)
return html_lib.unescape(m.group(1)).strip() if m else s
def main() -> int:
args = parse_args()
if not args.key:
logger.error("No 2captcha API key. Pass --key, or better, export TWOCAPTCHA_KEY.")
return 2
query = Query(mode="announcements", catalog=args.category or DEFAULT_ANN_CATALOG)
why = query.validate()
if why:
logger.error("%s", why)
return 2
rows, seen, pages_done, failed = [], set(), 0, []
stop_reason, blocked, total, available = "completed", False, None, None
plan = args.pages
page = 1
while page <= plan:
req = request_for(query, page)
args.url = req.url
rc, text, status = _fetch_once(args)
if rc:
failed.append(page)
stop_reason = "blocked_aws-waf" if rc == 3 else "page_load_timeout"
blocked = rc == 3
break
state = detect_page_state(text, status, req.url)
if state == "rejected":
logger.error("The endpoint refused this request (%s).",
api_error(text) or "HTTP 400, empty body")
failed.append(page)
stop_reason = "api_rejected"
break
if state not in ("content", "empty"):
logger.error("Page %d came back as %s (upstream HTTP %s).", page,
state, status)
failed.append(page)
blocked = state in ("challenge", "blocked", "restricted")
stop_reason = "blocked_aws-waf" if state == "challenge" else (
"blocked_geo-451" if state == "restricted" else
"blocked_http-403" if state == "blocked" else "page_load_timeout")
break
got = parse_page(text, query, page)
pages_done += 1
if page == 1:
total = total_results(text, "announcements")
available = pages_available(total, "announcements")
plan = pages_to_fetch(args.pages, available)
logger.info("Parsed %d announcement(s) from page %d.", len(got), page)
if not got:
stop_reason = "end_of_listing"
break
rows.extend(dedupe_by_key(got, seen))
page += 1
if page <= plan:
time.sleep(args.delay)
return finish_run(rows, args.out, args.format, args.allow_empty,
blocked=blocked, stop_reason=stop_reason,
pages_requested=args.pages, pages_completed=pages_done,
pages_failed=failed, mode="announcements",
source=SOURCE_DEFAULT,
start_url=request_for(query, 1).url,
final_url=request_for(query, max(1, pages_done)).url,
extra={"total_results": total,
"pages_available": available,
"query": {"catalog": query.catalog},
"engine": "scraper_api"})
def _fetch_once(args):
"""(rc, json_text, upstream_status). rc is 0 on a fetch that returned,
EXIT_API_ERROR on the API failing, 3 on a WAF page after the retries."""
attempts = max(1, args.retries + 1)
for attempt in range(1, attempts + 1):
try:
body, upstream_status = fetch_html(args)
except requests.RequestException as e:
logger.error("Network error talking to the Scraper API: %s", e)
return EXIT_API_ERROR, "", None
except RuntimeError as e:
logger.error("%s", e)
return EXIT_API_ERROR, "", None
text = json_text(body)
if args.dump_html:
with open(args.dump_html, "w", encoding="utf-8") as f:
f.write(text)
logger.info("Response written to %s", args.dump_html)
if detect_page_state(text, upstream_status, args.url) != "challenge":
return 0, text, upstream_status
if attempt < attempts:
logger.info("AWS WAF page on attempt %d/%d — retrying in %ds.",
attempt, attempts, args.retry_delay)
time.sleep(args.retry_delay)
logger.error("The Scraper API's fetch met AWS WAF on every attempt. Route "
"it through a Scraping Browser session (--cdp-url), or use a "
"browser engine.")
return 3, "", None
def parse_args():
p = argparse.ArgumentParser(
description="binance.com scraper — 2captcha Scraper API edition (no "
"local browser). Reads --mode announcements, the one GET "
"endpoint; the P2P and copy-trading endpoints are POST "
"only and this client does not implement them.")
# NOT required: prefer the TWOCAPTCHA_KEY env var (a key in argv is
# visible to anyone who can run `ps`).
p.add_argument("--key", default=os.environ.get("TWOCAPTCHA_KEY"),
help="2captcha.com API key (sent as a Bearer token). "
"Defaults to $TWOCAPTCHA_KEY, which is the safer way to pass it.")
p.add_argument("--mode", choices=["p2p", "copytrading", "announcements"],
default="announcements",
help="announcements (default, and the only one this client "
"implements). p2p and copytrading are refused with the "
"reason: their endpoints are POST only.")
p.add_argument("--category", default=None,
help="The announcement catalogue: %s, or a numeric id "
"(default %s)." % (", ".join(ANN_CATALOGS), DEFAULT_ANN_CATALOG))
p.add_argument("--pages", type=int, default=1,
help="Pages of 50 announcements (default 1).")
p.add_argument("--delay", type=float, default=1.0,
help="Seconds between pages (default 1.0)")
p.add_argument("--format", choices=["json", "csv", "both"], default="both")
p.add_argument("--out", default="binance_rows_scraperapi", help="Output file prefix")
p.add_argument("--timeout", type=int, default=60,
help=f"API-side task timeout in seconds (1-{MAX_API_TIMEOUT}, default 60)")
p.add_argument("--cdp-url", default=None,
help="Route the fetch through an existing browser session over CDP "
"(sent as the API's `cdpurl` param), e.g. ws://user:pass@host:port")
wait = p.add_mutually_exclusive_group()
wait.add_argument("--wait-text", default=None,
help="Wait until this string appears on the page.")
wait.add_argument("--wait-element", default=None,
help="Wait until this CSS selector is visible.")
wait.add_argument("--wait-state", choices=["load", "domcontentloaded"], default=None,
help="Wait for a page load state instead of specific content")
p.add_argument("--allow-empty", action="store_true",
help="Write output files even when 0 rows were parsed.")
p.add_argument("--retries", type=int, default=1,
help="Extra attempts if a WAF page comes back. Each attempt is "
"a separate billable task, so this defaults to 1.")
p.add_argument("--retry-delay", type=int, default=10,
help="Seconds between retries (default 10)")
p.add_argument("--dump-html", default=None,
help="Also write the response (JSON) to this path, even on success")
args = p.parse_args()
args.url = None
# This client uses --key and --cdp-url rather than --twocaptcha-key and
# --cdp-endpoint, so the env mapping is spelled out instead of defaulted.
env_config.apply(args, keys={
"TWOCAPTCHA_KEY": "key",
"BINANCE_CDP_ENDPOINT": "cdp_url",
})
if args.mode != "announcements":
p.error("--mode %s is not implemented by this client: its endpoint "
"answers POST only, and the Scraper API fetches a URL. Use "
"playwright_scraper.py, puppeteer_scraper.py or "
"selenium_scraper.py for it." % args.mode)
if catalog_id(args.category or DEFAULT_ANN_CATALOG) is None:
p.error("--category must be one of %s, or a numeric catalogue id"
% ", ".join(ANN_CATALOGS))
if args.pages < 1:
p.error("--pages must be at least 1")
return args
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(1)