Skip to content

About

Open-source TikTok ads scraper in Python for the TikTok Ad Library. Export advertisers, creatives, run dates and audience buckets to JSON or CSV.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

9 stars

Watchers

0 watching

Forks

Latest commit

 

History

30 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TikTok Ads Scraper — TikTok Ad Library Ads, Advertisers and Creatives in Python

release tests canary python licence engines runs without an account

TikTok ads scraper — an open-source (MIT) Python tool that reads the TikTok Ad Library, TikTok's EU ad library at library.tiktok.com and writes each ad's advertiser, creatives and media URLs, first and last shown dates and TikTok's audience bucket, across 33 regions, to JSON or CSV. It needs no account and no proxy. One header minted by the library's own JavaScript gates the search, so a browser is a prerequisite, and since 2026-11-23 the search is also behind a captcha, which the engines solve through a 2Captcha API key (measured 2026-12-02). Use it to build a dataset of ads by region or advertiser, or compare two runs with diff_runs.py.

Extract advertisements from TikTok's EU Ad Library — the advertiser, the creatives, the dates an ad ran, TikTok's own audience bucket, and the policy reason where an ad was rejected. 33 regions.

Playwright, Selenium or Puppeteer. No account, no proxy; a 2Captcha key for the search's captcha (since 2026-11-23).

Example output

[
  {
    "source": "library.tiktok.com",
    "scraped_at": "2026-09-22T22:26:45Z",
    "url": "https://library.tiktok.com/ads/detail/?ad_id=1877066373930178&region=DE",
    "sku": "1877066373930178",
    "title": "back in stock & buy more save more today only!!!!",
    "ad_id": "1877066373930178",
    "row_key": "DE:1877066373930178",
    "advertiser_name": "安徽金尚机械制造股份有限公司",
    "region": "DE",
    "first_shown_at": "2026-09-22T22:03:03+00:00",
    "last_shown_at": "2026-09-22T22:03:03+00:00",
    "days_shown": 0,
    "creative_type": "video+image",
    "video_count": 1,
    "image_count": 1,
    "video_urls": [
      "https://library.tiktok.com/api/v1/cdn/1790116006/video/aHR0c…"
    ],
    "cover_urls": [
      "https://p16-common-sign.tiktokcdn.com/ad-site-i18n-sg/202609…"
    ],
    "image_urls": [
      "https://p16-common-sign.tiktokcdn.com/ad-site-i18n-sg/202609…"
    ],
    "audit_status": "1",
    "sor_audit_status": "1",
    "show_mode": 1,
    "ad_type": "2",
    "rejection_info": null,
    "estimated_audience": "0-1K",
    "page": 1,
    "position": 3
  },
  {
    "source": "library.tiktok.com",
    "scraped_at": "2026-09-22T22:26:45Z",
    "url": "https://library.tiktok.com/ads/detail/?ad_id=1877066062400801&region=DE",
    "sku": "1877066062400801",
    "title": "регистрируйся по ссылке",
    "ad_id": "1877066062400801",
    "row_key": "DE:1877066062400801",
    "advertiser_name": null,
    "region": "DE",
    "first_shown_at": "2026-09-22T21:52:44+00:00",
    "last_shown_at": "2026-09-22T21:52:44+00:00",
    "days_shown": 0,
    "creative_type": "image",
    "video_count": null,
    "image_count": 1,
    "video_urls": null,
    "cover_urls": null,
    "image_urls": [
      "https://p16-common-sign.tiktokcdn.com/ad-site-i18n-sg/202609…"
    ],
    "audit_status": "1",
    "sor_audit_status": "3",
    "show_mode": 2,
    "ad_type": "2",
    "rejection_info": "{\"affected_regions\": [\"DK\"], \"automated_notice\": \"we have used automated measures in making this decision.\", \"hit_illegal_content_reason\": 0, \"reasons\": [\"Our review shows that your advertising content may violate TikTok's advertising policies by promoting misleading employment or money-making opportunities. This may include unclear job or opportunity descriptions, misleading language about qualification requirements, or instructions for users to communicate outside the platform\"], \"reporting_source\": \"We proactively enforce our Advertising Policies through a mix of technology and human moderation. We have detected this policy violation using automated measures.\"}",
    "estimated_audience": "0-1K",
    "page": 2,
    "position": 10
  }
]

Two of the rows in sample_output.json (21 rows, 26 columns), read from region DE, two cursor pages, on 2026-09-22. Media URLs are shortened here; the file holds them whole. The second ad is published without an advertiser name and carries TikTok's own policy reason in rejection_info. The sample predates the captcha of 2026-11-23; the columns have not changed since.

Requirements and access

Runtime Python 3.9 or newer; Playwright with its Chromium (recommended), Selenium or pyppeteer — one engine per virtualenv. A browser is required, not a fallback: one header that gates the search is minted by the library's own JavaScript (see Why a browser)
Coverage TikTok's EU Ad Library (library.tiktok.com): each ad's advertiser, creatives and media URLs, first and last shown dates, TikTok's audience bucket and, on a rejected ad, its policy reason, in 33 regions (the EU/EEA, CH, GB and TR). No account or login. See Coverage and limitations
Required for the documented scenario A 2Captcha API key (TWOCAPTCHA_KEY), since 2026-11-23: every search has a captcha in front of it, and the engines solve it in the page (see Captchas). Without a key the run exits 3 (blocked)
Not required A TikTok account or a proxy. The captcha appeared for every client measured on 2026-12-02 — a GitHub runner and a Hetzner server with no proxy, and a Scraping Browser profile — so a different exit does not avoid it
Optional: 2Captcha Scraping Browser API --cdp-endpoint (TIKTOK_CDP_ENDPOINT): runs the browser remotely instead of on your machine. The same key solves the captcha there; the canary's Scraping Browser job (an EU country-de profile) collected 36 ads on 2026-12-03
Optional: a proxy --proxy / --proxy-file (TIKTOK_PROXY): another exit; not needed for any measured scenario
Cost Captcha solving is billed per solve: about $0.0012 a solve on 2026-12-02, one to three solves a run. --max-solves caps a run (default 6; up to 3 for one page)
Measured 2026-12-03 at commit fb4bd7a: the weekly canary from a bare GitHub runner and through a Scraping Browser profile, both green. See Verification

Quick start

git clone https://github.com/2scraper/tiktok-ads-scraper
cd tiktok-ads-scraper
python3 -m venv venv
./venv/bin/pip install -r requirements.txt -r requirements-playwright.txt
./venv/bin/python -m playwright install chromium
cp .env.example .env       # then set TWOCAPTCHA_KEY in it (see Captchas)
./venv/bin/python playwright_scraper.py --region DE

It writes tiktok_ads.json (--out sets the prefix; --format csv or both for CSV) and tiktok_ads.meta.json beside it, with the run's status, why each region stopped, the solves spent and the share of the library the run covered. The default is three cursor pages, up to 36 ads per region.

If the run does not end with exit 0:

  • exit 3, blocked — the captcha was not solved: no key, --solve-captcha never, --max-solves spent, or every answer refused. Set TWOCAPTCHA_KEY and run again.
  • exit 4, zero ads — the library answered total: 0, for example a --query that matched nothing. That is a real answer.
  • exit 5 or 6, not obtained or partial — 5: no ads were obtained (including a response that states ads exist and carries none, or a browser that could not start); 6: some ads were saved, then a region stopped early or its listing was cut short. See Exit codes.

Setup, .env and exit codes for the whole family: How to run the 2scraper scrapers.

One clone, one virtualenv. The four tiktok-* repos share top-level module names (product_parser, output_writer, playwright_scraper, …), so pip install . of two of them into one environment makes the second silently replace the first. The commands above never do that — keep it that way, and give each repo its own venv.

Several regions, deeper, both formats:

./venv/bin/python playwright_scraper.py --region DE,FR,GB,IT \
    --pages 10 --days 90 --format both

A named advertiser:

./venv/bin/python playwright_scraper.py --region DE --query nike

Coverage and limitations

  • 33 regions, and only those. The library covers the EU/EEA, Switzerland, the UK and Turkey; --region US is refused with that reason (see Scope).
  • Twelve ads a request, and a vast catalogue. The library reported 17,343,646 ads for Germany alone; a hundred-page run holds 1,200 of them. A complete run is not an exhaustive one: the sidecar records sample_share_pct (see Complete is not exhaustive).
  • An ad id is not unique across regions. The same EU ad buy is listed in several member states; rows join on row_key ({region}:{ad_id}). See Read this before you trust a page count.
  • No spend or impressions. TikTok publishes both fields and both were empty on all 216 ads measured, so they are not columns (see What you get).
  • A captcha in front of every search since 2026-11-23, solved with a paid 2Captcha key; 8 of 13 answers were accepted on 2026-12-02, and a refused answer costs another solve.
  • A keyword search matches more than the advertiser's name, so --query returns resellers too.
  • No 2Captcha Scraper API path. A service that fetches a URL cannot mint the header the search needs; the three browser engines do the job.

Examples

Several regions, a named advertiser and every flag are under Quick start and --help; comparing two runs is diff_runs.py.

Verification

Date, commit Check Conditions Result
2026-12-03, fb4bd7a Canary, dispatched by hand a bare GitHub runner, no proxy, TWOCAPTCHA_KEY, --max-solves 3, regions DE, FR and GB green: 66 ads (DE 21, FR 21, GB 24), status complete, 2 paid solves; the keyword control was served too
2026-12-03, fb4bd7a Same run, the Scraping Browser job a 2Captcha Scraping Browser profile (country-de), the same key first attempt: 2Captcha returned its one answer as unsolvable and the run stopped, exit 3 (a retry within the budget is proposed in #23); a rerun of the job: green, 36 ads, 1 solve
2026-12-03, 9b37df1 Quick start, offline core requirements only every flag in the Quick start commands is in --help; .env.example lists every variable the code reads; sample_output.json matches the row schema; smoke_test.py and .github/ci_checks.py --all pass. The command was not re-run live in this pass: its scenario needs a paid key, and the canary above runs it
2026-12-02 Captcha solving, all three engines GitHub runners, no proxy 8 of 13 answers accepted, about $0.0012 and 16–79 s a solve, one to three solves a run; each engine obtained two cursor pages of ads after a solve
2026-12-02 Access a GitHub runner and a Hetzner server with no proxy, a Scraping Browser profile; headless or headful every search answered HTTP 200 with an empty body and a captcha — the gate since 2026-11-23
2026-09-22 Access, before the captcha a Hetzner datacentre address, no credentials served: HTTP 200, 12 ads; without the x-ccl-str header, HTTP 421

Captchas

Since 2026-11-23 the Ad Library puts a captcha in front of the search. Measured 2026-12-02 from a GitHub runner and a Hetzner server with no proxy, and through a Scraping Browser profile; headless or headful; with cookies accepted or declined. The search answers HTTP 200 with an empty body and a bdturing-verify header, and the page opens a captcha dialog.

The engines report that state as a captcha (it used to read as an empty refusal) and, with a key and --solve-captcha when-blocked (the default), solve it in the page:

  1. open the library with the whole search in its address (the page then searches by itself; a clicked Search on the bare page sent no request on 2026-12-02);
  2. send the challenge image to 2Captcha's CoordinatesTask as PNG (the page's own image is WebP, which the task refuses; the page converts it, so no imaging library is needed), click the two points that come back, and press Confirm;
  3. a refused answer loads a new image: it is reported with reportIncorrect and answered again, as a new solve;
  4. after "Verification complete", open the search again — the page's own retried search got HTTP 421 — and keep the token it sends.

Measured 2026-12-02 on GitHub runners: about $0.0012 a solve and 16–79 s each; 8 of 13 answers were accepted, and a run needed one to three solves. Each image is one paid solve, and every solve counts against --max-solves (default 6 for the whole run; up to 3 for one page). --solve-captcha never, no key, or a spent budget stop solving and the run reports it as blocked (exit 3, or 6 with the ads already saved). The sidecar records solves_spent and max_solves.

After a solve the search request must carry the page's own client parameters (aid, app_name, screen_width, …): this repo's earlier request answered HTTP 421 "system busy" with a fresh token, while the page's own request was served (2026-12-02). They are copied from the request the page really sent.

Why a browser

library.tiktok.com is TikTok's advertising transparency library, run to satisfy EU/EEA obligations. Its search endpoint is a plain POST. Measured 2026-09-22 from Hetzner, Helsinki, before the captcha of 2026-11-23, it was served to a bare datacentre address with no credentials of any kind:

request result
the browser's headers HTTP 200, 12 ads
the same, minus x-ccl-str HTTP 421
content-type + user-agent + referer + x-ccl-str only HTTP 200, 12 ads

So exactly one header gates it — and that header is minted by the library'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.

That makes a browser a prerequisite here, not a fallback — the reverse of tiktok-profile-scraper and tiktok-video-scraper, whose pages are server-rendered. The engine opens the library, lets it search once, keeps the header it sent, and every request after that is a cheap POST. --transport http is refused up front with that reason rather than failing later on a 421 nobody can interpret.

Read this before you trust a page count

offset is a decoy. The request body carries one, the library's own UI increments it, and it does nothing: measured, 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:

{"last_sort": [1790109992000], "next_cursor": 12}

A scraper that trusted offset would re-collect page one for as long as it was asked to and report a complete run of duplicates. This repo reads the cursor, and reads the END of the listing out of it too — a cursor that stops advancing ends the run whatever has_more claims.

limit is a decoy too. 12, 50 and 100 all return twelve.

And an ad id is not unique. An EU ad buy commonly runs in several member states at once and the library lists it under each. Measured, page one of five regions fetched within the same few seconds:

pair ad ids shared
DE vs IT 11 of 12
DE vs FR 9 of 12
DE vs PL 9 of 12
DE vs GB 1 of 12

GB is outside the EU and is bought separately, which is exactly the shape you would expect. So every row carries row_key ({region}:{ad_id}) and that is what deduping and diffing join on. Before it existed, a two-region run collapsed France's twelve ads to two.

Complete is not exhaustive, and here the gap is enormous

The library reports 17,343,646 ads for Germany alone and serves twelve per request. A thorough hundred-page run holds 1,200 of them — 0.0069%.

Every run records site_total_per_region, ads_per_region and sample_share_pct in its sidecar, and the closing log prints the fraction in words. A run that fetched every page it asked for is complete; it is not exhaustive, and the two are different sentences.

The sidecar also records why_each_region_stopped — cursor_exhausted, cursor_stalled, has_more_false, short_page or no_ads — so "we stopped" is never just a number.

A short page under a large total is an incomplete run, not the end. The library serves twelve ads per page: 45 of the 47 cursor pages in the canary's artifacts from 2026-10-09 to 2026-10-15 (when it still ran daily) carried exactly twelve. Both exceptions came from one run on 2026-10-13. France's first page carried two ads, with has_more: false beside total: 17,071,905, and Germany's second page carried eleven. The library documents no cap that would explain that, so a page with fewer than twelve ads, while the response's own total says more remain, is a listing cut short. The run keeps the ads it got, records each such page under short_pages, ends with stop_reason: short_page and status partial, and exits 6. A short last page that brings the count up to the total is the real end of the listing, and the run is complete.

What you get

26 columns per ad. The ones worth naming:

column note
sku, ad_id the ad id — not unique across regions
row_key {region}:{ad_id}, which is
advertiser_name 211 of 216 measured carry one; five are published anonymously
region which of the 33 the ad was found in — a column, because the same ad runs in several
first_shown_at, last_shown_at, days_shown TikTok publishes these in milliseconds; read as seconds they land in the year 58,700
creative_type, video_count, image_count derived from the creatives the ad carries, not from show_mode, whose meaning TikTok documents nowhere
video_urls, cover_urls, image_urls the library's own proxied media URLs, which answer HTTP 302 to the real files
estimated_audience TikTok's bucket, e.g. "0-1K" — a string, because it is a range and turning it into a number would be a guess
rejection_info TikTok's own policy reason on a rejected ad. 2 of 216 measured, and stored in a canonical (sorted-key) form so two byte-equal responses cannot diff against each other
audit_status, sor_audit_status, show_mode, ad_type TikTok's own values, passed through unmapped

CSV cells that a spreadsheet would run as a formula are escaped. A text cell beginning with =, +, -, @, a tab or a line break gets a leading ' in the CSV only; numbers and the JSON output are unchanged, and the sidecar's csv_cells_escaped says how many cells were touched. Output files are written atomically and follow your umask; an existing file keeps its mode.

impression and spent are not columns. TikTok publishes both fields on every ad and both were empty on all 216 measured across six regions and three pages each. The likely reason is that the EU rules attach spend and reach to political advertising and TikTok prohibits political advertising outright — so they may be structurally empty rather than sparse. The measurement is recorded in output_writer.py so anyone can add them back with a better one.

Scope: 33 regions, and the rest of the world is not one of them

AT BE BG CH CY CZ DE DK EE ES FI FR GB GR HR HU IE IS IT LI LT
LU LV MT NL NO PL PT RO SE SI SK TR

--region US is refused with that reason — it is a real country the library does not cover, not a typo. Measured: region=US and region=BR return a body that is not JSON at all, while DE, FR and GB return ads.

Exit codes

code meaning
0 ok
1 crash
2 bad usage
3 blocked — including the search's captcha left unsolved: no key, --solve-captcha never, --max-solves spent, or every answer refused
4 zero ads — including "the query matched nothing", which is a real answer (the library says total: 0)
5 the content was never obtained — including a response that states ads exist (total above zero or has_more true) and carries none
6 partial — including a region whose listing was cut short (fewer than twelve ads on a page while the stated total says more remain)

A run that finds nothing writes nothing, so an earlier good output survives.

--allow-empty is for a genuine empty result only. With it, a run that finished and found nothing writes an empty JSON ([]), a CSV holding only its header, and a sidecar with status: empty and its stop_reason, and still exits 4. It never turns a blocked or failed run into an empty one. A blocked run still exits 3. A run whose content was never obtained, including a response that states ads exist and carries none, still exits 5. A run that saved ads and then stopped early, a cut-short listing included, still exits 6. For the zero-row failures no empty row file is written, and an earlier output at the same --out is left untouched, sidecar included. Only when nothing earlier exists there does a blocked or failed --allow-empty run write a sidecar on its own, with status: blocked or failed. diff_runs.py compares an empty run like a complete one.

--query filters since v0.1.2, and did not before. Until then the keyword was sent without the search type the library's own UI sends, and the library ignored it: measured 2026-09-29 in DE over the same window, nike and a nonsense word both answered the whole region (19,000,309 and 19,000,308); with the type, nike answered 416 and the nonsense word 0. A keyword search matches more than the advertiser's name, so rows from resellers are expected. The sidecar records query, query_type, ad_type and window_days, and diff_runs.py refuses two runs that asked different questions.

An HTTP 421 mid-run is not a block: it means the token went stale, and the remedy is to mint another, which the run does by re-priming. Rotating an exit would spend a proxy budget on the wrong problem.

Configuration

cp .env.example .env
python3 env_config.py      # prints what was picked up, WITHOUT printing secrets

Variables: TWOCAPTCHA_KEY, TIKTOK_CDP_ENDPOINT, TIKTOK_PROXY, TIKTOK_URL. TWOCAPTCHA_KEY is needed since 2026-11-23 for the search's captcha (see Captchas); the others are optional.

The 2Captcha Scraper API path is deliberately not implemented here, and the distinction matters: a service that fetches a URL cannot mint a header for a request it is not making. That is a feature request, not a limitation of the product — and the three browser engines do the job.

The weekly canary

.github/workflows/canary.yml runs a real scrape every Monday from a bare GitHub runner with no proxy, and is expected green. Since 2026-11-23 that runner meets the captcha too, so the job passes the TWOCAPTCHA_KEY repository secret and caps each run at three paid solves (--max-solves 3); without the secret it fails and names it. It asserts that the run recorded its solves and stayed within the cap.

A second job runs the same scrape through a 2Captcha Scraping Browser profile from the TIKTOK_CDP_ENDPOINT secret, with the same key, and fails naming either secret when it is not set.

FAQ

Does TikTok Ads have a public API?

This repository does not use one. It reads the search endpoint that the Ad Library's own page calls, a plain POST that answers only with the x-ccl-str header the page's JavaScript mints, so each run opens the page in a browser first and then sends the search itself. See Why a browser.

Is there a TikTok Ads scraper API?

No hosted API: this is a command-line tool you run yourself, and one command writes the rows to JSON or CSV with a .meta.json file beside them that records whether the run completed. To run it on a schedule, put the Quick start command in cron or a CI job.

Do I need a key, a proxy or an account?

A 2Captcha API key, since 2026-11-23: every search has a captcha in front of it, and without a key the run exits 3. No proxy and no TikTok account: the canary collected 66 ads from a bare GitHub runner with only the key on 2026-12-03. A solve cost about $0.0012 on 2026-12-02, and --max-solves caps a run.

Is it legal to scrape library.tiktok.com?

This is not legal advice. Scraping public pages is permitted in many jurisdictions, but TikTok's terms of service, copyright in ad creatives and data-protection law differ between countries. The Ad Library is a public transparency library and the tool reads it without an account. Keep the request rate low and do not collect personal data without a lawful basis.

Why does TikTok Ads block headless browsers or datacenter IPs?

In the measurements here, neither the address nor headless mode decided access. On 2026-09-22 a bare datacentre address was served; since 2026-11-23 every search meets a captcha whatever the client — a GitHub runner, a Hetzner server, a Scraping Browser profile, headless or headful (2026-12-02). What refuses a plain HTTP client is the x-ccl-str header (HTTP 421 without it), which only the page's JavaScript mints. An unsolved captcha ends the run as exit 3, never 4.

How do I run the TikTok Ads scraper on a server?

Put TWOCAPTCHA_KEY in .env and run the Quick start command (Playwright runs headless by default); no proxy is needed. The weekly canary does exactly that on a GitHub runner, capped at --max-solves 3. Branch on the exit code and on status in the .meta.json.

What fields does the scraper return?

One row per ad and region: ad_id, row_key, advertiser_name, region, first_shown_at, last_shown_at, days_shown, creative_type, the media URLs, estimated_audience, rejection_info and TikTok's own status values — 26 columns. See What you get.

How often does it break when library.tiktok.com changes?

It broke on 2026-11-23, when the captcha appeared in front of every search and the page changed its own search request; the engines solve it since 2026-12-03 (v0.2.1 and earlier do not). Earlier, until v0.1.2, the library ignored --query because the scraper omitted the search type. The weekly canary runs a real scrape from a GitHub runner and through a Scraping Browser profile; fixes are recorded in CHANGELOG.md.

Related scrapers

Same CLI conventions, same output contract (one row per item, JSON or CSV, a .meta.json sidecar and shared exit codes):

All scrapers: github.com/2scraper · Need another site? Open a request

Contributing

python3 smoke_test.py       # the offline suite — no network, no browser needed
python3 -m pytest

Licence

MIT. See LICENSE.

Captcha solving, the Scraping Browser API, proxies and fingerprints are four separately-billed 2Captcha products behind one key. This repo uses captcha solving for the captcha in front of the search (since 2026-11-23); the Scraping Browser API, proxies and fingerprints are optional.

About

Open-source TikTok ads scraper in Python for the TikTok Ad Library. Export advertisers, creatives, run dates and audience buckets to JSON or CSV.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

9 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages