Repository navigation
Expand file tree
/
Copy pathselenium_scraper.py
More file actions
1618 lines (1443 loc) · 73.3 KB
/
Copy pathselenium_scraper.py
File metadata and controls
1618 lines (1443 loc) · 73.3 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""selenium_scraper.py — TikTok's EU Ad Library.
python3 selenium_scraper.py --region DE
python3 selenium_scraper.py --region DE,FR,GB --pages 5 --format both
python3 selenium_scraper.py --region IT --query nike --days 90
One header gates the whole thing
================================
`library.tiktok.com` is TikTok's advertising transparency library for the
EU/EEA plus GB, CH, NO, IS, LI and TR — 33 regions, taken from the site's
own `/api/v1/support-regions` rather than guessed.
Its search endpoint is a plain POST served to a bare datacentre address
with no key, no account and no cookies. Measured 2026-09-22 from Hetzner,
Helsinki:
with the browser's headers HTTP 200, 12 ads
the same, minus `x-ccl-str` HTTP 421
content-type + user-agent + referer + x-ccl-str HTTP 200, 12 ads
So exactly one header gates it, and the page's own JavaScript mints it —
there is no global to read it out of, and a plain `fetch` issued from
inside the page gets 421 too, because the app attaches it in its own HTTP
client.
This engine therefore drives a browser for ONE purpose: open the library,
let it search once, and keep the header it sent. Everything after that is
a cheap POST. `--transport http` is refused with that reason rather than
failing later on a 421 nobody can interpret.
That makes this repo the reverse of tiktok-profile-scraper and
tiktok-video-scraper, whose pages are server-rendered and who treat the browser as a fallback. Gating is
per-ROUTE, and so is the remedy.
`offset` is a decoy
===================
The request body carries an `offset`, the site's own UI increments it, and
it does nothing: offsets 0, 12 and 24 returned the identical twelve ads in
the identical order. Pagination is by `search_id`, a base64 cursor the
response hands back, and the end of the listing is read from that cursor
rather than from `has_more`. `limit` is a decoy too — 12, 50 and 100 all
return twelve.
A run that trusted `offset` would re-collect page one for as long as it
was asked to and report a complete run of duplicates.
"""
import argparse
import json
import logging
import queue
import sys
import threading
import time
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
# Imported at MODULE level on purpose — see the note in
# puppeteer_scraper.py. smoke_test.py asserts it.
from selenium import webdriver
from selenium.common.exceptions import (WebDriverException,
TimeoutException as SETimeout)
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.common.by import By
from captcha_solver import (detect_recaptcha_v3, detect_recaptcha_in_page,
reconcile_detections, solve_recaptcha,
CaptchaUnsolvable, INJECT_TOKEN_JS,
RECAPTCHA_DISCOVERY_JS, SHAPE_ABSENT,
SHAPE_SOLVED, solve_shape_captcha)
from output_writer import (COMPLETE_STOP_REASONS, Advertisement,
dedupe_by_key, finish_run,
utc_now, EXIT_API_ERROR, EXIT_NO_PRODUCTS,
SOURCE_DEFAULT)
import page_flow
from page_flow import SolveBudget
from http_transport import HttpSession, TransportError
import product_parser as parser
from product_parser import (ADS_PER_PAGE, NotAnAdsQuery, STATE_CONTENT,
STATE_EMPTY_SUCCESS, STATE_NO_ADS,
STATE_SHAPE_CAPTCHA, STATE_TOKEN_REJECTED,
STATE_UNKNOWN, TOKEN_HEADER, detect_page_state,
library_url, normalise_region, parse_search,
search_body, search_url)
from tiktok_payload import PayloadError
from proxy_pool import (from_args as proxy_pool_from_args, to_playwright, mask,
ROTATE_MODES, ProxyError, ProxyPool)
import env_config
logging.basicConfig(level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger("selenium_scraper")
# The one name the shared logic below uses for "the driver failed". Each
# engine binds it to its own library's exception, so everything from
# `_prime_session` downwards is byte-comparable across the three — which is
# what makes "the engines must agree" checkable rather than aspirational.
DriverError = (WebDriverException, SETimeout)
MODES = ("ads",)
DEFAULT_MODE = "ads"
ENGINE_NAME = "selenium"
# Every remote call is bounded.
REQUEST_TIMEOUT_MS = 30_000
NAVIGATION_TIMEOUT_MS = 60_000
MIN_CARD_MATCHES = page_flow.MIN_CARD_MATCHES
@dataclass
class PageOutcome:
"""One fetch attempt's result, in request order rather than arrival order.
Merging by arrival order makes the output depend on which
worker finished first. Workers return these and the caller sorts.
"""
number: int
url: str = ""
rows: List[Any] = field(default_factory=list)
state: str = STATE_UNKNOWN
status: Optional[int] = None
blocked: bool = False
error: Optional[str] = None
diagnostics: Dict[str, Any] = field(default_factory=dict)
attempted: bool = True
def _mask_credentials(text: Any) -> str:
"""Mask every credential in a string, not just the first.
A masker that handles the first occurrence prints the
password the other four times and looks like it is working — Playwright
repeats a CDP endpoint five times in one error, once in the message and
four more in its call log.
"""
import re
out = str(text)
out = re.sub(r"(?i)\b((?:client)?key|token|api[_-]?key|password)=[^&\s\"']+",
r"\1=***", out)
# The login too, not only the password: a Scraping Browser login is
# the account and profile id, and a connect failure printed it in
# full (2026-12-02).
out = re.sub(r"(wss?://)([^:/@\s]+):([^@\s]+)@", r"\1***:***@", out)
return out
def _chrome_ua(chromium_version: str) -> str:
"""A user agent built from the Chromium actually installed.
A hardcoded version drifts from whatever is installed,
and claiming an older Chrome than the JS engine and TLS handshake
report is itself a mismatch.
"""
major = (chromium_version or "").split(".")[0] or "140"
return (f"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
f"(KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
def _proxy_failure(exc: Exception) -> str:
"""Name a dead proxy, or "" for anything else.
Chromium reports a dead proxy as a generic error, not a
timeout, and the two want opposite responses — a timeout deserves
another try at the SAME exit, a dead proxy a DIFFERENT one. Catching
only the timeout type let this escape as a traceback in a sibling repo.
"""
text = str(exc)
for marker in ("ERR_PROXY_CONNECTION_FAILED", "ERR_TUNNEL_CONNECTION_FAILED",
"ERR_PROXY_AUTH_UNSUPPORTED", "ERR_UNEXPECTED_PROXY_AUTH",
"ERR_PROXY_CERTIFICATE_INVALID"):
if marker in text:
return marker
return ""
# A `fetch` made from inside the page.
#
# On the site's own origin, so it carries the same cookies, the same proxy
# and the same user agent the browser has — which is the whole reason a
# browser is involved at all. A function EXPRESSION, never an evaluated
# string: TikTok's CSP does carry `unsafe-eval` today (measured
# 2026-09-22), but a CSP is a per-route header a site can tighten without
# notice, and a sibling repo's run died on exactly that.
_FETCH_JS = """
var spec = arguments[0];
var done = arguments[arguments.length - 1];
var init = {method: spec.method, headers: spec.headers,
credentials: 'include'};
if (spec.body) { init.body = spec.body; }
fetch(spec.url, init).then(function (response) {
return response.text().then(function (text) {
// The captcha is announced in a HEADER on an empty 200; both names are
// CORS-exposed, and this request is same-origin anyway.
done({status: response.status, text: text,
headers: {'bdturing-verify': response.headers.get('bdturing-verify'),
'x-vc-bdturing-parameters':
response.headers.get('x-vc-bdturing-parameters')}});
});
}).catch(function (err) {
done({status: null, text: null, error: String(err)});
});
"""
class _BrowserSession:
"""A driver, a page on tiktok.com, and a fetch primitive bound to it.
A rotation is a FRESH BROWSER: cookies a bot manager
issued against exit A and replayed from exit B are a stronger signal
than either address alone. So this object is torn down and rebuilt
rather than having its proxy swapped underneath it.
"""
def __init__(self, driver, proxy_url: Optional[str],
client_version: str, user_agent: Optional[str],
owns_driver: bool = True):
# Always True here: this engine cannot connect to a remote browser
# at all (see the module docstring), so it only ever ends a driver
# it started. The flag exists so the three sessions carry the same
# shape and `check_every_engine_exposes_the_same_public_surface`
# can say so.
self.owns_driver = owns_driver
self.driver = driver
self.browser = driver
self.context = driver
self.page = driver
self.proxy_url = proxy_url
self.client_version = client_version
self.user_agent = user_agent
# -- transport ---------------------------------------------------------
def _fetch(self, url: str, method: str = "GET",
headers: Optional[Dict[str, str]] = None,
body: Optional[str] = None):
spec = {"url": url, "method": method, "headers": headers or {},
"body": body}
try:
self.driver.set_script_timeout(REQUEST_TIMEOUT_MS / 1000.0)
return self.driver.execute_async_script(_FETCH_JS, spec)
except DriverError as exc:
raise _TransportError(_mask_credentials(exc)) from exc
def get_text(self, url: str) -> Tuple[Optional[int], Optional[str]]:
result = self._fetch(url) or {}
return result.get("status"), result.get("text")
def post_json(self, url: str, headers: Dict[str, str],
body: Dict[str, Any]) -> Tuple[Optional[int], Any]:
self.last_headers = {}
result = self._fetch(url, "POST", headers, json.dumps(body)) or {}
status, text = result.get("status"), result.get("text")
self.last_headers = {k: v for k, v in
(result.get("headers") or {}).items() if v}
if result.get("error"):
raise _TransportError(_mask_credentials(result["error"]))
try:
return status, json.loads(text) if text else None
except (TypeError, ValueError):
# A refusal is not JSON. Hand the body back as text so the
# classifier can name it rather than the run dying on a decode.
return status, text
def goto(self, url: str) -> Optional[int]:
self.driver.set_page_load_timeout(NAVIGATION_TIMEOUT_MS / 1000.0)
self.driver.get(url)
# Selenium reports no HTTP status for a navigation. That is a real
# gap on sites where the status IS the signal — but not here: every
# response this engine classifies comes back through `_fetch`,
# which carries the status from the page's own `fetch`. So nothing
# is discarded; there is simply nothing to discard at this call.
return None
def content(self) -> str:
try:
return self.driver.page_source or ""
except DriverError:
return ""
def count_selector(self, selector: str) -> int:
try:
return len(self.driver.find_elements(By.CSS_SELECTOR, selector))
except DriverError:
return 0
def evaluate(self, js: str, arg: Any = None) -> Any:
"""Run a function EXPRESSION in the page.
Wrapped in `return (…)(arg)` because `execute_script` takes a
function BODY, where the shared captcha module hands out `() =>
expr`. Never an evaluated string on the page's own terms: a site's
Content-Security-Policy has no `unsafe-eval`, and
`execute_script` goes through the WebDriver protocol rather than
through the page's `eval`.
"""
try:
if arg is not None:
return self.driver.execute_script(
f"return ({js})(arguments[0]);", arg)
return self.driver.execute_script(f"return ({js})();")
except DriverError:
return None
@property
def url(self) -> str:
try:
return self.driver.current_url or ""
except Exception:
return ""
def open_search(self, url: str, path_fragment: str,
header: str) -> Dict[str, Any]:
"""Selenium's dialect: CDP performance logs.
Selenium has no request-event API, so this reads Chrome's own
performance log for `Network.requestWillBeSent` (the token) and
`Network.responseReceived` (how TikTok answered). That needs
`goog:loggingPrefs` set at launch, which `_launch_local` does.
Returns {"nav_status", "token", "request", "status", "headers"}, a
key absent when that part never happened.
"""
seen: Dict[str, Any] = {}
ids = set()
try:
self.driver.execute_cdp_cmd("Network.enable", {})
except Exception: # noqa: BLE001
pass
try:
# Drop what an earlier page left in the log.
self.driver.get_log("performance")
except Exception: # noqa: BLE001
pass
def drain():
try:
entries = self.driver.get_log("performance")
except Exception: # noqa: BLE001
return
for entry in entries:
try:
message = json.loads(entry["message"])["message"]
except Exception: # noqa: BLE001
continue
params = message.get("params") or {}
method = message.get("method")
if method == "Network.requestWillBeSent":
request = params.get("request") or {}
if path_fragment not in request.get("url", ""):
continue
ids.add(params.get("requestId"))
headers = {k.lower(): v for k, v in
(request.get("headers") or {}).items()}
if headers.get(header.lower()) and "token" not in seen:
seen["token"] = headers[header.lower()]
seen["request"] = {"url": request.get("url"),
"body": request.get("postData")}
elif (method == "Network.responseReceived"
and params.get("requestId") in ids
and "status" not in seen):
response = params.get("response") or {}
seen["status"] = response.get("status")
seen["headers"] = dict(response.get("headers") or {})
try:
seen["nav_status"] = self.goto(url)
except DriverError as exc:
if _proxy_failure(exc):
raise
seen["nav_error"] = _mask_credentials(exc)
logger.warning("Could not open %s (%s)", url, seen["nav_error"])
if page_flow.navigation_interrupted(seen["nav_error"]):
# Cut short by the page's own navigation: the caller opens
# it again rather than waiting for a search that never left.
return seen
self._wait_until(drain, lambda: "status" in seen, 25)
if "token" not in seen:
# The page did not search by itself: press its Search, through
# `execute_script` — an element click captured nothing here.
page_flow.wait_for_count(
self.count_selector, page_flow.ready_selector(),
page_flow.min_matches(),
timeout_ms=page_flow.content_timeout_ms())
self._click_search()
self._wait_until(drain, lambda: "status" in seen, 20)
return seen
@staticmethod
def _wait_until(poll, done, seconds: float) -> None:
deadline = time.time() + seconds
while True:
poll()
if done() or time.time() >= deadline:
return
time.sleep(0.5)
def click_at(self, x: float, y: float) -> None:
"""A real mouse click at viewport coordinates, through CDP."""
try:
for kind in ("mouseMoved", "mousePressed", "mouseReleased"):
event = {"type": kind, "x": x, "y": y}
if kind != "mouseMoved":
event.update(button="left", clickCount=1)
self.driver.execute_cdp_cmd("Input.dispatchMouseEvent", event)
except DriverError as exc:
raise _TransportError(_mask_credentials(exc)) from exc
def _click_search(self):
try:
time.sleep(6)
for button in self.driver.find_elements(By.TAG_NAME, "button"):
if "search" in (button.text or "").strip().lower():
self.driver.execute_script("arguments[0].click();", button)
return True
except Exception: # noqa: BLE001
pass
return False
def close(self):
try:
self.driver.quit()
except Exception:
pass
class _TransportError(RuntimeError):
"""A transport-level failure, already masked."""
class _CaptchaBlocked(_TransportError):
"""TikTok's shape captcha stands in the way and was not solved.
A subclass, so every caller that already survives a failed mint
survives this too; the ones that can say "blocked" (exit 3) rather than
"not obtained" (exit 5) catch it first.
"""
class RemoteBrowserError(RuntimeError):
"""The remote-browser path is unavailable from this driver."""
# ---------------------------------------------------------------------------
# Launching
# ---------------------------------------------------------------------------
def _launch_local(pw, args, pool: Optional[ProxyPool]) -> _BrowserSession:
"""A local Chromium, optionally behind one exit from the pool."""
from proxy_pool import split_credentials
proxy_url = pool.current if pool else (args.proxy or None)
options = ChromeOptions()
# Chrome's performance log is how this engine captures the one header
# that gates the Ad Library — Selenium has no request-event API, so it
# reads `Network.requestWillBeSent` out of the log instead. Without
# this capability the log is empty and the token mint fails with a
# message about the Search button, which is the wrong place to look.
options.set_capability("goog:loggingPrefs", {"performance": "ALL"})
if args.headless:
options.add_argument("--headless=new")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--window-size=1366,900")
if proxy_url:
host_only, username, _password = split_credentials(proxy_url)
if username:
# Said out loud rather than silently dropped. Selenium cannot
# authenticate a proxy at all, and a user who passed a
# `user:pass` URL must not be left believing it is doing
# something.
logger.warning("Selenium cannot authenticate a proxy: the "
"credentials in --proxy have been STRIPPED and "
"only %s is in use. If this exit needs a "
"password, use the Playwright or pyppeteer "
"engine.", mask(proxy_url))
options.add_argument(f"--proxy-server={host_only}")
user_agent = None
fingerprint = None
if args.fingerprint:
from fingerprint_client import get_fingerprint, fingerprint_user_agent
fingerprint = get_fingerprint(args.twocaptcha_key, tags=args.fp_tags,
country=args.fp_country)
user_agent = fingerprint_user_agent(fingerprint)
if user_agent:
options.add_argument(f"--user-agent={user_agent}")
driver = webdriver.Chrome(options=options)
if not user_agent:
version = (driver.capabilities or {}).get("browserVersion", "")
user_agent = _chrome_ua(version)
if fingerprint is not None:
_apply_fingerprint(driver, fingerprint, user_agent)
return _BrowserSession(driver, proxy_url, "",
user_agent)
def _apply_fingerprint(driver, fingerprint, user_agent) -> None:
"""Give the identity everything the fingerprint states, not just a UA.
`--user-agent=` on the command line is a BARE override: it changes
`navigator.userAgent` and leaves `navigator.userAgentData` and the
`Sec-CH-UA` header reporting the real browser. A sibling site measured
that half-identity being refused where a complete one was served, so
this engine applies the same set its twins do.
Best effort throughout — a fingerprint is cover, and no run should die
because cover was imperfect.
"""
from fingerprint_client import (user_agent_metadata, accept_language,
playwright_init_script)
try:
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",
{"source": playwright_init_script(fingerprint)})
except DriverError as exc:
logger.warning("Could not install the fingerprint's init script: %s",
_mask_credentials(exc))
metadata = user_agent_metadata(fingerprint)
if not metadata:
logger.warning("The fingerprint carried no brand list, so its client "
"hints are left alone: a HALF identity is worse than "
"none.")
return
payload = {"userAgent": user_agent, "userAgentMetadata": metadata}
language = accept_language(fingerprint)
if language:
payload["acceptLanguage"] = language
platform = (fingerprint.get("navigator") or {}).get("platform")
if platform:
payload["platform"] = platform
try:
driver.execute_cdp_cmd("Network.setUserAgentOverride", payload)
timezone = (fingerprint.get("intl") or {}).get("timeZone")
if timezone:
driver.execute_cdp_cmd("Emulation.setTimezoneOverride",
{"timezoneId": timezone})
except DriverError as exc:
logger.warning("Could not apply the fingerprint's client hints (%s) — "
"the run continues, but navigator.userAgentData will "
"disagree with the user agent.",
_mask_credentials(exc))
def _connect_remote(pw, args) -> _BrowserSession:
"""Refused, with the reason — see this module's docstring.
chromedriver's `debuggerAddress` takes a bare `host:port` and has
nowhere to put a password, so the 2Captcha Scraping Browser endpoint —
`ws://{login}-zone-…:{password}@cb.2captcha.com:9222` — cannot be used
from here. Reporting that plainly is the whole point: the alternative
is an auth failure several steps away from its cause.
"""
raise RemoteBrowserError(
"--cdp-endpoint is not usable from the Selenium engine: "
"chromedriver's debuggerAddress takes a bare host:port and cannot "
"carry the endpoint's credentials. Use playwright_scraper.py or "
"puppeteer_scraper.py for the Scraping Browser API.")
def _open_http(args, pool: Optional[ProxyPool]) -> HttpSession:
"""Refused, and the reason is the whole architecture of this repo.
The search endpoint answers HTTP 421 to any request without a valid
`x-ccl-str`, and that header is generated by the page's own
JavaScript — there is no global to read it from, and a plain `fetch`
issued from inside the page gets 421 too, because the app attaches it
in its own HTTP client. Measured 2026-09-22.
So a browser is a PREREQUISITE here, not a fallback. The profile and
video repos are the other way round: their pages are server-rendered and the
browser is what `--transport auto` reaches for when the site
challenges. Saying which way round it is, per route, is the point.
"""
raise NotAnAdsQuery(
"--transport http cannot work against TikTok's Ad Library: the "
"search endpoint answers HTTP 421 without an `x-ccl-str` header "
"that only the page's own JavaScript can mint. Use the default "
"(--transport browser); the browser mints one token and the "
"requests after it are cheap.")
def _open_session(pw, args, pool: Optional[ProxyPool]):
if getattr(args, "transport", "browser") == "http":
return _open_http(args, pool)
session = (_connect_remote(pw, args) if args.cdp_endpoint
else _launch_local(pw, args, pool))
if args.proxy_rotate == "per-run" or not pool:
logger.info("Browser up%s", f" via {mask(session.proxy_url)}"
if session.proxy_url else "")
return session
# ---------------------------------------------------------------------------
# Minting the one header that gates the endpoint
# ---------------------------------------------------------------------------
def _prime_session(session, args, url: str,
budget: Optional[SolveBudget] = None) -> Optional[int]:
"""Open the Ad Library, let it search once, and keep its token.
This is the whole reason a browser is here. The app attaches
`x-ccl-str` to its own requests from inside its HTTP client, so the
only way to get one is to let the app make a request and watch.
`url` carries the whole search (`product_parser.library_url`): since
2026-12-02 that is the only way the page searches by itself.
The token is REUSABLE — verified by replaying a captured one through
curl and getting HTTP 200 with twelve ads — so one mint serves a whole
run, and a 421 later in the run means it went stale, which is its own
state (`token_rejected`) and is cured by minting another rather than
by rotating an exit.
When TikTok answers the page's search with its 3D shape captcha, the
dialog is solved in the page (each image bought through `budget`) and
the search is OPENED AGAIN: after "Verification complete" the page's
own retried search got HTTP 421 and its form reset, while opening the
same address again was served (measured 2026-12-02). Not solved — no
key, `--solve-captcha never`, the budget spent, every answer refused —
raises `_CaptchaBlocked`.
"""
if budget is None:
budget = SolveBudget(run=page_flow.run_budget(args))
status = None
rounds = reopens = 0
while True:
seen = session.open_search(url, parser.SEARCH_PATH, TOKEN_HEADER)
status = seen.get("nav_status", status)
state = (detect_page_state(b"", seen.get("status"), url,
seen.get("headers"))
if "status" in seen else None)
if state == STATE_SHAPE_CAPTCHA:
logger.warning("TikTok put a captcha in front of the library's "
"own search.")
# Each captcha round either buys a solve or ends the loop, so
# the budget bounds it; the +1 bounds a dialog never shown.
rounds += 1
if rounds > budget.limit + 1:
raise _CaptchaBlocked("The captcha in front of the search "
"kept coming back; the run is blocked.")
session.shape_captcha = True
# Third call site, same budget.
if handle_captcha_if_present(session, args, budget):
# The page resets itself after "Verification complete";
# opening the search during that navigation was aborted
# (net::ERR_ABORTED, 2026-12-02). Let it settle first.
time.sleep(page_flow.SETTLE_AFTER_SOLVE_S)
continue
raise _CaptchaBlocked(
"The captcha in front of the search was not solved, so no search "
"can be made: the run is blocked.")
token = seen.get("token")
if (not token and reopens < page_flow.REOPEN_RETRIES
and page_flow.navigation_interrupted(seen.get("nav_error"))):
# Transient: open it again. Never a solve.
reopens += 1
logger.warning("Opening the search was interrupted by the "
"page's own navigation; opening it again "
"(%d/%d).", reopens, page_flow.REOPEN_RETRIES)
time.sleep(page_flow.REOPEN_DELAY_S)
continue
if not token:
raise _TransportError(
f"could not mint an `{TOKEN_HEADER}` token from {url}. The Ad "
"Library's own search has to run once for the app to produce "
"one; if the page did not load or its Search button moved, "
"that is what to look at. Re-run with --dump-html to see what "
"arrived.")
session.search_token = token
session.search_request = seen.get("request")
logger.info("Minted an %s token (%d chars) — the run reuses it.",
TOKEN_HEADER, len(token))
return status
def handle_captcha_if_present(session, args, budget: SolveBudget) -> bool:
"""Route to the browser handler, or say why there is nothing to do.
The annotation on this used to promise a `_BrowserSession`, which
stopped being true the moment a transport without a page existed. On
the HTTP transport there is no document to inject a token into and no
DOM to detect a widget in, so this returns False and says so ONCE per
run rather than per page — a warning repeated forty times is a warning
nobody reads.
"""
if isinstance(session, HttpSession):
if args.solve_captcha != "never" and not getattr(
args, "_http_solve_warned", False):
args._http_solve_warned = True
logger.warning("A challenge cannot be solved on the HTTP "
"transport: there is no page to inject a token "
"into. --transport auto (the default) starts a "
"browser when the site refuses.")
return False
return _handle_captcha_in_browser(session, args, budget)
def _handle_captcha_in_browser(session, args,
budget: SolveBudget) -> bool:
"""Detect and, if it is worth paying for, solve a challenge.
Both call sites — before classification and after — go through the same
`SolveBudget`, which is the fix: `SOLVES_PER_PAGE` read
like an enforced limit in every repo in this family and was not one,
because only the second of the two calls was counted. One page bought
three solves on a site where a challenge rendered on every fetch.
A missing key or a solver error is a WARNING and the run continues:
detection is not the same as blocking, and a run that
already has data must not die because a solve failed.
"""
shape = bool(getattr(session, "shape_captcha", False))
session.shape_captcha = False
if args.solve_captcha == "never":
if shape:
logger.error("A captcha in front of the search is in the way and "
"--solve-captcha is never: not solving it, so the "
"run reports it as blocked (exit 3).")
return False
if shape:
return _solve_shape_in_browser(session, args, budget)
html = session.content()
if not html:
return False
static = detect_recaptcha_v3(html, session.url)
live = None
try:
live = detect_recaptcha_in_page(session.evaluate, session.url)
except Exception: # noqa: BLE001
live = None
challenge = reconcile_detections(static, live)
if challenge is None:
return False
if not budget.may_spend():
logger.warning("A challenge is present and this page's solve budget "
"(%d) is already spent — not paying twice for one "
"page.", budget.limit)
return False
if not args.twocaptcha_key:
logger.warning("A captcha is present and no --twocaptcha-key was "
"given; continuing unsolved. The run reports exit 3 "
"if it really was blocked.")
return False
if not budget.spend():
return False
if args.cdp_endpoint:
# The token is MINTED over plain HTTPS from this machine and then
# installed into a browser that is somewhere else entirely. A
# Scraping Browser endpoint carries a `country-` segment, so the
# solve can be issued on one continent and replayed from another —
# and a token a challenge issuer binds to the solving address is
# then worthless on arrival. Said out loud rather than left to be
# discovered from a bill: nothing here can fix it, and the remedy
# is the endpoint's own auto-solve (`Captcha.setAutoSolve`), which
# runs where the browser is.
logger.warning("Solving over --cdp-endpoint mints the token from "
"THIS machine and installs it into a remote browser, "
"so it may be issued on a different exit than the one "
"that will use it. If the token is refused, that is "
"the likeliest reason.")
try:
token = solve_recaptcha(challenge, args.twocaptcha_key,
min_score=args.min_score,
api_version=args.captcha_api)
except CaptchaUnsolvable as exc:
logger.warning("Captcha not solved: %s", _mask_credentials(exc))
return False
except Exception as exc: # noqa: BLE001
logger.warning("Captcha solver failed: %s", _mask_credentials(exc))
return False
if session.evaluate(INJECT_TOKEN_JS, token) is None:
logger.warning("Could not inject the solved token into the page.")
return False
logger.info("Captcha solved and token injected.")
return True
def _solve_shape_in_browser(session, args, budget: SolveBudget) -> bool:
"""TikTok's 3D shape dialog, answered in the page through 2Captcha.
Every image bought goes through `budget.spend()` inside
`solve_shape_captcha`; the budget draws on the run's `--max-solves`.
"""
if not args.twocaptcha_key:
logger.error("A captcha in front of the search is in the way and no "
"2Captcha key is "
"configured (--twocaptcha-key or TWOCAPTCHA_KEY), so it "
"cannot be solved. The run reports it as blocked "
"(exit 3).")
return False
if not budget.may_spend():
logger.error("A captcha in front of the search is in the way and the solve "
"budget is spent (%d this page, --max-solves %d this "
"run): not buying another.", budget.limit,
page_flow.run_budget(args).limit)
return False
outcome = solve_shape_captcha(session.evaluate, session.click_at,
args.twocaptcha_key, budget)
if outcome == SHAPE_SOLVED:
return True
if outcome == SHAPE_ABSENT:
logger.warning("The search announced a captcha, but no "
"dialog appeared on the page; nothing was bought.")
else:
logger.error("The captcha in front of the search was not solved (%s).",
outcome)
return False
# ---------------------------------------------------------------------------
# One fetch, with the family's retry / block policy around it
# ---------------------------------------------------------------------------
def _dump(args, name: str, payload: Any) -> None:
"""Write the exact bytes a call returned.
On SUCCESS too, not only on failure: a run can return
the right count with a field silently unpopulated, and then the exact
payload is the only way to tell a parsing bug from a too-early
snapshot.
"""
if not args.dump_html:
return
path = f"{args.out}_{name}.json"
try:
with open(path, "w", encoding="utf-8") as handle:
if isinstance(payload, (dict, list)):
json.dump(payload, handle, ensure_ascii=False)
else:
handle.write(str(payload))
logger.info("Wrote %s", path)
except OSError as exc:
logger.warning("Could not write %s: %s", path, exc)
def _call(session, args, url: str, body: Dict[str, Any], budget: SolveBudget,
label: str) -> Tuple[Optional[int], Any, str]:
"""One search POST, with the minted token, and classify the answer."""
headers = {
"content-type": "application/json",
"accept": "application/json, text/plain, */*",
"referer": parser.UI_URL,
TOKEN_HEADER: getattr(session, "search_token", "") or "",
}
# The page's own client parameters ride along: without them the
# endpoint answered 421 after a solved captcha (2026-12-02).
url = parser.with_client_params(url, getattr(session, "search_request",
None))
status, payload = session.post_json(url, headers, body)
state = detect_page_state(payload, status, url,
getattr(session, "last_headers", None))
logger.debug("%s -> http %s, state %s", label, status, state)
return status, payload, state
def _fetch_with_policy(session_box: Dict[str, Any], pw, args,
pool: Optional[ProxyPool], url: str,
body: Dict[str, Any], label: str
) -> Tuple[Optional[int], Any, str, bool]:
"""One call plus the retry / rotate / solve policy around it.
`session_box` holds the live session so a rotation can replace it: a
rotation is a fresh browser, never a proxy swapped under a live
session.
"""
budget = SolveBudget(run=page_flow.run_budget(args))
attempts = max(1, int(args.retries) + 1)
blocked_seen = False
status = payload = None
state = STATE_UNKNOWN
# A while rather than a for: switching transport below grants
# one more attempt, and range() is fixed when the loop starts.
attempt = 0
while attempt < attempts:
attempt += 1
session = session_box["session"]
# First of the two solve call sites: clear a challenge BEFORE the
# answer is judged, so a gated page is not classified on its
# interstitial.
if args.solve_captcha == "always":
handle_captcha_if_present(session, args, budget)
try:
status, payload, state = _call(session, args, url, body,
budget, label)
except (_TransportError, TransportError) as exc:
state = parser.STATE_ERROR
payload = str(exc)
status = None
exit_failed = _proxy_failure(exc)
if exit_failed:
# A dead proxy is NOT a timeout, and the two want opposite
# responses: a timeout deserves another try at the SAME
# exit, a dead proxy a DIFFERENT one. Chromium reports it
# as a generic error rather than as a timeout, which is how
# this escaped as a traceback in a sibling repo.
logger.warning("%s failed at the EXIT, not at the site: %s "
"via %s. Rotating rather than retrying the "
"same address.", label, exit_failed,
mask(session.proxy_url))
if pool:
pool.advance(exit_failed)
session_box["session"].close()
session_box["session"] = _open_session(pw, args, pool)
_prime_session(session_box["session"], args,
session_box["prime_url"])
else:
logger.warning("%s failed after %d attempt(s): %s",
label, attempt, exc)
if state == STATE_TOKEN_REJECTED:
# HTTP 421. The remedy is a fresh token, not a fresh exit —
# so the session is re-primed in place rather than rotated,
# and this is NOT counted as a block.
logger.info("%s: the %s token was rejected; minting another.",
label, TOKEN_HEADER)
try:
_prime_session(session_box["session"], args,
session_box["prime_url"])
except Exception as exc: # noqa: BLE001
logger.error("could not mint a fresh token: %s",
_mask_credentials(exc))
break
if state == STATE_SHAPE_CAPTCHA:
# The captcha is answered in the page, where its dialog is: the
# library's own search is opened again, solved there, and the
# token re-minted. Our own request carries no dialog to answer.
blocked_seen = True
logger.warning("%s: TikTok answered with a captcha in front of the search; "
"opening the library's search to solve it.", label)
spent = budget.spent
try:
_prime_session(session_box["session"], args,
session_box["prime_url"], budget)
except _TransportError as exc:
logger.error("%s: %s", label, _mask_credentials(exc))
break
if budget.spent > spent:
# A solve is not a retry: the page is asked again, and the
# budget, not --retries, bounds how often that happens.
attempts += 1
continue
if page_flow.counts_as_blocked(state):
blocked_seen = True
# `auto` means HTTP until the site says otherwise, and this is
# otherwise. An HTTP client has nowhere to put a solved token,
# no cookie jar a challenge issuer will accept and no DOM to
# find a widget in, so the only useful response to a refusal is
# to stop being an HTTP client.
#
# Once per run, and then never again: a site that challenged
# once will challenge again, and flapping between transports
# would pay the browser's start-up cost on every page while
# looking like it was trying something new.
if (getattr(args, "transport", "auto") == "auto"
and isinstance(session_box["session"], HttpSession)):
logger.warning("%s was refused over plain HTTP (%s) — "
"starting a browser and retrying. This is "
"what --transport auto is for, and it happens "
"once per run.", label, state)
session_box["session"].close()
args.transport = "browser"
session_box["session"] = _open_session(pw, args, pool)
_prime_session(session_box["session"], args,
session_box["prime_url"])
# The switch is not a retry: it is the same page asked
# through the transport that can answer it. Without the
# extra attempt, `--retries 0` started a browser and
# never asked it for the page (audit 2026-09-29).
attempts += 1
continue
# Second call site, same budget.
if page_flow.should_solve(state):
handle_captcha_if_present(session, args, budget)
if not page_flow.should_retry(state) or attempt >= attempts:
break
if page_flow.counts_as_blocked(state):
if not page_flow.RETRY_ON_BLOCKED:
break
budget_left = (args.proxy_block_retries if pool
else page_flow.BLOCK_RETRIES_WITHOUT_POOL)
if attempt > budget_left:
break
if pool and pool.rotates_per_page():
pool.advance(f"state {state}")
logger.info("Rotating exit and rebuilding the browser — a "
"rotation is a fresh browser, never a proxy "
"swapped under a live session.")
session_box["session"].close()