TikTok Scraper in Python with Astro Proxies

03 December 2026

image

The script collects available statistics for public TikTok profiles and individual videos from your lists. Followers, likes, views and other metrics can be exported to CSV for Excel and to JSON for further processing. No TikTok login is required.

Below you’ll find the Windows setup, run commands and how to work with the results. The guide comes with the TikTok_Astro_Start.zip archive: the script, dependencies, list files and a quick start guide. The full code is also provided at the end of this document.

Free Trial and Astro Bonuses

  • 100 MB of free trial traffic after  sign-up.
  • Cumulative discount of up to 25%. The discount rate depends on your  total top-up amount.
  • Referral program – up to 15% of referred users’ spending, under the  program terms.


What Data Goes into the Export

Figure 1. What the script collects: profile and video fields, export formats.

Item

Fields

Profile – 9 fields

Username, display name, profile bio, verification badge, followers, following, total account likes, number of videos, profile link

Video – 13 fields

ID, author, description, publication date in UTC, views, likes, comment count, shares, saves, hashtags, track title, duration in seconds, link

The script extracts these fields from a JSON data block embedded in the page HTML. Whether a value is available depends on TikTok’s response and how it is parsed. An empty cell means the value was not recorded; see Step 8 for how to check the export.

This kind of collection helps you compare pre-selected accounts, track public metrics of ad posts and analyze descriptions, hashtags and tracks from a prepared list of links. The script doesn’t search for creators or videos by niche and doesn’t retrieve an account’s full list of posts. For comments, only the count is saved.

Which Proxies to Choose

A proxy lets you set the connection location and send requests from an external IP in the selected pool. For TikTok, you can use Astro mobile or residential proxies. Mobile IPs are well suited for tasks that require high success rates and a lower risk of blocks. Residential IPs from real users are indistinguishable from regular residential traffic – a reliable solution for data collection.

In this guide, we use a US residential port with the “Change IP by link” rotation mode. Rotate IPs for free on a timer, with every new connection, or manually (via a rotation link or directly in the dashboard). Choose the country based on where the content you need is available, and keep the same location settings for repeat measurements.

Step 1. Install Python

This guide is for PowerShell on Windows 10 or Windows 11 and Python 3.10 or later. The library version used is curl_cffi 0.17.0; the original example was prepared with Python 3.15.2.

Install the Python install manager from the official website, open PowerShell and run:

python --version

If the manager offers to install a Python runtime, complete the installation and run the command again. If you see the >>> prompt instead of PowerShell, type exit(): the remaining commands run in the terminal, not in the interactive Python shell. If the command doesn’t work, see the Python guide for Windows.

Step 2. Prepare the Folder and Dependencies

Unzip TikTok_Astro_Start.zip and open the TikTok_Astro_Start folder inside. It contains:

File

Purpose

tiktok_scraper.py

Script

requirements.txt

Dependency

users.txt

Profile list; already contains tiktok

videos.txt

Video list; contains only comments for now

README_EN.txt

Quick start guide

If you use the code from the end of this document, save it as plain text named tiktok_scraper.py, keeping the indentation, and save the dependency block as requirements.txt. Turn on file name extensions in File Explorer and make sure no extra .txt was added to the names.

Open PowerShell in the folder with the files. In Windows 11, you can right-click the folder and select “Open in Terminal”; make sure the PowerShell tab is open. Alternatively, run cd with your own path:

cd 'C:\Users\NAME\Downloads\TikTok_Astro_Start'

Create a separate environment and install the library. Each line is a separate command:

python -m venv .venv

.\.venv\Scripts\python.exe -m pip install -r requirements.txt "curl_cffi==0.17.0"

You don’t need to activate the environment: the following commands call its interpreter directly. Wait for the installation to finish without errors. curl_cffi lets the script use Chrome’s network profile; the script doesn’t execute the page’s JavaScript and doesn’t solve CAPTCHAs.

Step 3. Create an Astro Port

Open the Ports section and the “Port options” form.

Field

Example setting

Network type

Residential; for mobile proxies – Mobile

Country

United States or another suitable country

City and Operator

Any, unless you need precise targeting

Change external IP address

Change IP by link

Tariff

Prepaid traffic

Traffic volume

An available package that fits your task and balance

Check the price shown in the dashboard before saving. To start, choose a small available package; the 1 GB in the screenshot is an example setting, not a required purchase volume.

Figure 2. Example of a residential port in the US. The $7.60 price applies to a 1 GB configuration for one month at the time the example was prepared. Check the current price in your dashboard.

Step 4. Set Up the Connection

In the port card, copy the “Server”, “Login” and “Pass” values and the port number from the “HTTP(S)” field. Insert them into this string:

http://LOGIN:PASSWORD@SERVER:PORT

Figure 3. Connection string: all values come from the port card in your Astro dashboard.

The http:// scheme refers to the connection to the proxy; TikTok page URLs remain HTTPS. The script also accepts https://, socks5:// and socks5h://: use the protocol that matches your port settings. For SOCKS, take the port number from the “SOCKS” field; socks5h:// lets the proxy resolve the target site’s hostname, while socks5:// leaves resolution to the client.

If your login or password contains special characters such as @, :, # or an apostrophe, URL-encode them within the credentials. Quotation marks in the command don’t replace encoding. Astro support can help you get a ready-to-use connection string.

Set the proxy in the current PowerShell window:

$env:TT_PROXY='http://LOGIN:PASSWORD@SERVER:PORT'

The script reads TT_PROXY, so you don’t need --proxy in the following commands. If both are set, --proxy takes priority. In a new PowerShell window, set the variable again.

For the “Change IP by link” mode, copy the IP rotation link from your dashboard. Like TT_PROXY, this variable must be set again in a new PowerShell window:

$rotate='IP_ROTATION_LINK'

The connection string and the rotation link may contain access credentials. Don’t share them in screenshots or reports, and keep in mind that commands may be saved in your terminal history.

Step 5. Collect Data from a Single Page

For the first run, use the tiktok profile. The first command creates a file prefix with the date and time; run it again before each batch:

$out='tiktok_' + (Get-Date -Format 'yyyyMMdd_HHmmss')

.\.venv\Scripts\python.exe tiktok_scraper.py --users 'tiktok' --out $out

For a single video, use the separate commands below. First, replace the entire placeholder link with the link to your video:

$video='https://www.tiktok.com/@username/video/1234567890123456789'

$out='tiktok_' + (Get-Date -Format 'yyyyMMdd_HHmmss')

.\.venv\Scripts\python.exe tiktok_scraper.py --videos $video --out $out

The script first sends a request to the TikTok home page, then checks the external address via api.ipify.org and prints “External IP”. This line refers to the check request and doesn’t lock the IP for the entire run. If the check fails, the script exits with the “Proxy is not responding” message; see the troubleshooting section below.

An “ok” line means the parser returned a record. “Done” shows the number of records retrieved and the number of failed list items. Before using the data, run the checks in Step 8.

Step 6. Fill In the Lists

In users.txt, enter usernames one per line, with or without @. Don’t paste full profile links here:

# One username per line

tiktok

In videos.txt, add full direct links to your videos. The following link only shows the structure and must be replaced:

# One video URL per line

https://www.tiktok.com/@username/video/1234567890123456789

Remove duplicates. Empty lines are skipped, as are lines that start with # once leading and trailing spaces are removed. Comments after a username or URL on the same line are not supported.

The list files in the archive are saved as UTF-8 without BOM. Keep this encoding after editing: the script doesn’t strip the BOM, and this marker can corrupt the first entry. In VS Code, click the encoding indicator in the bottom-right corner → Save with Encoding → UTF-8. Don’t choose UTF-8 with BOM.

You can also pass a short list directly in the command, separated by commas. In PowerShell, use quotes, for example --users '@tiktok,YOUR_USERNAME', replacing the second item with your username.

Step 7. Process the Lists

Make sure users.txt and videos.txt are in the working folder. If a file isn’t found, the script may treat its name as a username or page URL.

$out='tiktok_' + (Get-Date -Format 'yyyyMMdd_HHmmss')

.\.venv\Scripts\python.exe tiktok_scraper.py --users users.txt --videos videos.txt --out $out --change-ip-url $rotate

Enter the second command on a single line. For profiles only, remove --videos videos.txt; for videos only, remove --users users.txt. If you don’t use automatic calls to the rotation link, remove --change-ip-url $rotate.

Pages are processed sequentially. Split large lists into batches: CSV and JSON files are written only after all lists are processed, and progress isn’t saved automatically. Wait for the script to finish and use a new prefix for the next batch.

Step 8. Import and Check the Results

The files appear in the current working folder with the prefix you chose. Without --out, tiktok_result is used.

File

Contents

<prefix>_users.csv

Profile records retrieved

<prefix>_videos.csv

Video records retrieved

<prefix>.json

Profile and video data, plus the failed list of URLs that couldn’t be processed

A CSV file is created only if it has rows. If you reuse a prefix, JSON and CSV files with new rows are overwritten, while a CSV without new rows may remain from a previous run. A new prefix for each batch helps keep exports from different dates separate.

Importing into Excel

Keep the original CSV unchanged. If you simply open the file, Excel may convert long IDs to numbers and lose some digits, and may interpret user text as formulas. Import the data as follows:

1. In Excel, go to Data → From Text/CSV and select the file.

2. Choose UTF-8 and the actual delimiter; by default, the script uses ;.

3. Click Transform Data. In Power Query, delete the automatic Changed Type step if there is one.

4. Select all columns and set their type to Text at the source import step, before any numeric conversions. Check the full video_id against the original CSV.

5. Load the data and save a working copy as XLSX. For calculations, convert only the verified counter columns; keep IDs, links, names and descriptions as text.

Menu names may vary by Excel version. If corrupted IDs have already been saved over the CSV, restore the original copy or collect the data again: changing the cell format won’t bring back the lost digits. See Microsoft’s guidance on long numbers.

Checking the Data

Match usernames, authors and video IDs against the original pages and check the metrics your report’s conclusions rely on. The url field stores the original request URL; on its own, it doesn’t confirm that all the extracted statistics belong to that item. Exclude disputed rows until they are verified independently.

Specifics of this version of the parser:

  • In the fallback SIGI_STATE format, the first objects found are used. If there are several, the wrong record may be selected and a profile may be matched with the wrong statistics.
  • If the main JSON block is parsed successfully but doesn’t contain the required data, the fallback block is not checked. A non-empty but incomplete statsV2 is not supplemented with fields from stats.
  • In some responses, a zero total-likes count for a profile may appear as an empty cell or be replaced with a fallback value. Don’t automatically treat empty cells as zeros.

An empty failed list doesn’t prove that all fields are complete. TikTok’s interface may round values, and statistics may change between requests; keep this in mind when verifying, but don’t use it to explain every discrepancy.

The reasons for failed attempts are shown in the terminal. The failed list in the JSON contains only URLs, without the reasons. To collect them again, move video links to videos.txt and profile usernames to users.txt, and set a new output prefix.

Request Retries and IP Rotation

By default, each page gets up to three attempts. HTTP 403, 429 and 5xx are explicitly treated as failures. Network errors, missing data and parsing errors can also trigger a retry. The script doesn’t determine which of these can be resolved by changing the IP.

If attempts remain and --change-ip-url is set, the script calls the rotation link, waits 5 seconds, creates a new HTTP session and sends a request to the TikTok home page. It then adds a pause of 2 seconds before the second attempt or 4 seconds before the third. The actual wait time includes network operations.

Figure 4. IP rotation via link when a request is retried with --change-ip-url set.

In the source code, the “IP changed via link” message means the HTTP call completed without an exception. The script doesn’t check the service’s response status or content, or the new IP. As a result, a retry may sometimes run from the previous address.

Without --change-ip-url, requests are retried with pauses, without calling the link or creating a new session. The --delay parameter sets the pause between pages, not between attempts for the same page. The dynamic external IP may also change depending on your port settings or network conditions.

The rotation link is called without the proxy from the --proxy argument; however, other environment variables with proxy settings may affect connections. Keep this in mind when running without TT_PROXY as well. Cookies persist within the HTTP session, so individual requests are not fully independent of its state.

Command-Line Options

Option

Purpose

Default

--proxy

Proxy address; otherwise TT_PROXY is used

TT_PROXY value, if set

--users

Username file or comma-separated list

Not set

--videos

URL file or comma-separated list

Not set

--change-ip-url

Port’s IP rotation link

Not set

--delay

Average pause between pages, seconds

4

--retries

Attempts per page

3

--timeout

Timeout for a single network request, seconds

30

--out

Output file prefix

tiktok_result

--sep

CSV delimiter

;

The pause between pages is random: from half to one and a half times the --delay value, that is, 2–6 seconds with a value of 4. Use a non-negative --delay, an integer --retries of at least 1, a positive integer --timeout and a single-character delimiter. The code doesn’t validate all of these conditions in advance. The folder in the --out path must exist.

Troubleshooting

Command or File Not Found

Check the working folder, file extensions and whether the .venv environment exists. If you see the >>> prompt, exit with exit(). Output such as @users.txt or an attempt to open videos.txt as a URL usually means the list file wasn’t found.

Connection Check Fails

If you see “Unsupported proxy syntax”, make sure the template has been replaced with real data. Double-check the server, port, login, password and protocol. For IP-based authorization, add your computer’s current external IP to the allowlist. The “Proxy is not responding” message may also be related to ipify availability, so check both directions.

TikTok Returns Errors or a Page Without Data

Possible causes include rate limiting, a CAPTCHA, regional unavailability, a deleted post or a changed page structure. After the last failed attempt, the URL is added to the failed list; if non-empty HTML was received on that attempt, it is saved to the debug folder.

Open the HTML in a text editor and check the original link. The names page_1.html, page_2.html and so on are reused across runs, so save diagnostics separately if needed. If you get a series of HTTP 429 errors, reduce the next batch, increase the pause between pages and wait before starting a new run. Retry-After is not handled automatically. Changing the IP won’t fix deleted content or a parsing error.

Run Time and Traffic Usage

Run time depends on list size, pauses, response speed and retries. The script downloads HTML but doesn’t separately download videos, images or JavaScript files from the page. Additional traffic comes from preliminary requests to the TikTok home page, the IP check, redirects and retries.

To estimate your budget, note the “Traffic consumption” value in the port card before the run and after a small batch completes. Record the number of successful and failed items and the run parameters. Use this measurement as a guide for a similar sample, with a margin for retries.

The cost of the selected configuration is shown in the dashboard before purchase, and usage is shown in the “Traffic consumption” line of the port card. The package price in the screenshot is not the cost of a single run. Astro bills only for the dominant traffic type – inbound or outbound – rather than total traffic volume. Prepaid traffic starting from 100 MB and Pay-As-You-Go billing based on actual usage are available.

Astro Infrastructure Features

Since 2018, Astro has been building its own proxy infrastructure for businesses and teams working with online data collection, monitoring and analytics. The IP pool includes 50 million ethically sourced IP addresses across 150 countries, with 99.9% uptime.

  • IP targeting by country, city and ISP is available across all proxy types. Select up to 10 countries on a single port. A random country option is also available, with the ability to exclude up to 10 countries from the pool.
  • Private and dedicated proxies: each proxy is assigned to a single client and can be accessed via username/password authentication or IP allowlisting.
  • Built-in IP rotation. Rotate IPs for free on a timer, with every new connection, or manually (via a rotation link or directly in the dashboard).
  • HTTP(S) and SOCKS5 for scrapers, anti-detect browsers, headless browsers, AI bots, automated testing tools and custom solutions.
  • Up to 250 TCP connections per port and a full-featured API for automating proxy management at scale.
  • Proxy usage and traffic analytics, with the ability to organize ports by projects or use cases and download port lists as a single file.
  • VPN-compatible proxies with OpenVPN integration via a ready-to-use configuration file, plus Xray support.

Parallel connections and uptime are characteristics of Astro’s infrastructure. This script sends requests sequentially; page availability and data completeness also depend on TikTok and the parser.

FAQ

Can I run the script without a proxy?

The code allows you to run it without --proxy and TT_PROXY and prints a warning in that case. Page availability depends on TikTok’s response and your computer’s network settings.

Are datacenter proxies suitable?

Astro datacenter proxies are designed for automation, large-scale data collection and high-volume workloads where scalability and cost efficiency matter. This guide uses a residential port. For your project, choose the proxy type based on the availability of the pages you need and the cost of collection.

How do I use the export in regular reports?

Save separate exports with the run date and time, and check the data before comparing. created_utc is the video’s publication date, and likes_total is the account’s total likes. Views are not the same as unique reach or conversions.

This version doesn’t provide a per-row collection timestamp, a stable profile ID or automatic period-over-period comparison. If a username changes, match the account separately. For automated runs, check the output itself: the program’s exit code alone doesn’t confirm successful collection.

How do I run it on macOS or Linux?

The code doesn’t use any Windows-specific features. Create the environment with python3 -m venv .venv, then install the dependencies and run the script with .venv/bin/python. Set the proxy with export TT_PROXY='http://LOGIN:PASSWORD@SERVER:PORT'. PowerShell commands with $env: and Get-Date don’t work in these shells; you can set the --out prefix manually. Whether a suitable curl_cffi build is available depends on your system and architecture.

What rules should I follow?

The script works with public page data without logging in and doesn’t provide access to private content. Before use, review the applicable TikTok terms and make sure you have the necessary permissions for automated collection. Changes to the page structure may require updating the parser.

To set up a connection, create an Astro account and activate your free trial. For questions about ports and proxies, contact Astro support.

Full Code

The requirements.txt and tiktok_scraper.py files below match the files in the archive. The listing is provided as is, including comments and indentation.

The comment still mentions Python 3.9+; to install by following this guide, use Python 3.10+ and curl_cffi 0.17.0. The multi-line example with \ inside the comment is intended for a POSIX shell. In PowerShell, use the commands from Steps 5 and 7. The meaning of the “IP changed via link” message is explained in the section on retries.

Dependencies

File requirements.txt.

curl_cffi>=0.7

Script

File tiktok_scraper.py.

#!/usr/bin/env python3

"""

Simple scraper for public TikTok data via a proxy.

 

What it collects

  Videos by URL: author, description, publication date, views, likes,

  comments, shares, saves, hashtags, music, duration.

  Profiles by username: name, bio, verification, followers, following,

  total likes, number of videos.

 

Installation (Python 3.9+)

  python -m pip install curl_cffi

 

Usage

  python tiktok_scraper.py --proxy http://LOGIN:PASSWORD@HOST:PORT \

      --videos videos.txt --users users.txt --out result

 

  videos.txt  – one video URL per line

                (https://www.tiktok.com/@user/video/1234567890)

  users.txt   – one username per line (with or without @)

 

  Instead of files, you can pass comma-separated values:

      --videos "https://www.tiktok.com/@a/video/1,https://www.tiktok.com/@b/video/2"

      --users "nasa,@natgeo"

 

Proxy

  Format: http://LOGIN:PASSWORD@HOST:PORT

  Supported schemes: http://, https://, socks5:// and socks5h://.

  Instead of --proxy, you can set the TT_PROXY environment variable.

 

IP rotation via link

  If the port uses link-based IP rotation, pass the link with

  --change-ip-url. When TikTok returns an error (403, 429, 5xx) or

  a page without data, the script calls the link, waits and retries

  the request. Without this option, the script simply retries after a pause.

 

Output

  <out>_videos.csv, <out>_users.csv and <out>.json. CSV files are created

  only if there is data. The default CSV delimiter is ";", which Excel

  with many European regional settings (e.g. Russian or German) splits into

  columns right away (use --sep "," for US/UK settings).

  If a page cannot be parsed, its HTML is saved to the debug/ folder

  so you can see exactly what TikTok returned.

 

The script collects only public data visible on the page without

logging in. Before use, review TikTok's terms of use and avoid

sending requests too often.

"""

 

import argparse

import csv

import json

import os

import random

import re

import sys

import time

from datetime import datetime, timezone

 

try:

    from curl_cffi import requests as cffi_requests

except ImportError:  # HTML parsing can be tested without curl_cffi

    cffi_requests = None



UNIVERSAL_RE = re.compile(

    r'<script[^>]+id="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>(.*?)</script>', re.S

)

SIGI_RE = re.compile(r'<script[^>]+id="SIGI_STATE"[^>]*>(.*?)</script>', re.S)

 

HEADERS = {

    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",

    "Accept-Language": "en-US,en;q=0.9",

    "Referer": "https://www.tiktok.com/",

}

 

IP_CHECK_URL = "https://api.ipify.org?format=json"



class NoDataError(Exception):

    """TikTok returned a page, but it contains no usable data."""



# ---------------------------------------------------------------------------

# HTML parsing

# ---------------------------------------------------------------------------

 

def to_int(value):

    try:

        return int(value)

    except (TypeError, ValueError):

        return None



def extract_state(html):

    """Extracts the page data JSON. TikTok embeds it in a <script> tag."""

    for kind, pattern in (("universal", UNIVERSAL_RE), ("sigi", SIGI_RE)):

        match = pattern.search(html)

        if match:

            try:

                return kind, json.loads(match.group(1))

            except json.JSONDecodeError:

                continue

    return None, None



def video_row(item):

    stats = item.get("statsV2") or item.get("stats") or {}

    author = item.get("author")

    author_name = author.get("uniqueId") if isinstance(author, dict) else author

 

    tags = [t.get("hashtagName") for t in item.get("textExtra") or [] if t.get("hashtagName")]

    if not tags:

        tags = [c.get("title") for c in item.get("challenges") or [] if c.get("title")]

 

    created = to_int(item.get("createTime"))

    return {

        "video_id": item.get("id"),

        "author": author_name,

        "description": item.get("desc"),

        "created_utc": datetime.fromtimestamp(created, tz=timezone.utc).isoformat() if created else "",

        "views": to_int(stats.get("playCount")),

        "likes": to_int(stats.get("diggCount")),

        "comments": to_int(stats.get("commentCount")),

        "shares": to_int(stats.get("shareCount")),

        "saves": to_int(stats.get("collectCount")),

        "hashtags": " ".join("#" + t for t in tags),

        "music": (item.get("music") or {}).get("title"),

        "duration_sec": to_int((item.get("video") or {}).get("duration")),

    }



def parse_video(html):

    kind, data = extract_state(html)

    item, status = None, None

    if kind == "universal":

        detail = (data.get("__DEFAULT_SCOPE__") or {}).get("webapp.video-detail") or {}

        item = (detail.get("itemInfo") or {}).get("itemStruct")

        status = detail.get("statusCode")

    elif kind == "sigi":

        items = data.get("ItemModule") or {}

        item = next(iter(items.values()), None)

    if not item:

        raise NoDataError(f"no video data (statusCode={status})")

    return video_row(item)



def user_row(user, stats):

    return {

        "username": user.get("uniqueId"),

        "nickname": user.get("nickname"),

        "bio": user.get("signature"),

        "verified": user.get("verified"),

        "followers": to_int(stats.get("followerCount")),

        "following": to_int(stats.get("followingCount")),

        "likes_total": to_int(stats.get("heartCount") or stats.get("heart")),

        "videos": to_int(stats.get("videoCount")),

    }



def parse_user(html):

    kind, data = extract_state(html)

    user, stats, status = None, {}, None

    if kind == "universal":

        detail = (data.get("__DEFAULT_SCOPE__") or {}).get("webapp.user-detail") or {}

        info = detail.get("userInfo") or {}

        user = info.get("user")

        stats = info.get("statsV2") or info.get("stats") or {}

        status = detail.get("statusCode")

    elif kind == "sigi":

        module = data.get("UserModule") or {}

        user = next(iter((module.get("users") or {}).values()), None)

        stats = next(iter((module.get("stats") or {}).values()), {}) or {}

    if not user:

        raise NoDataError(f"no profile data (statusCode={status})")

    return user_row(user, stats)



# ---------------------------------------------------------------------------

# Fetching pages via the proxy

# ---------------------------------------------------------------------------

 

class Fetcher:

    def __init__(self, proxy, change_ip_url, delay, retries, timeout):

        if cffi_requests is None:

            sys.exit("curl_cffi is not installed. Run: pip install curl_cffi")

        self.proxies = {"http": proxy, "https": proxy} if proxy else None

        self.change_ip_url = change_ip_url

        self.delay = delay

        self.retries = retries

        self.timeout = timeout

        self.debug_counter = 0

        self._new_session()

 

    def _new_session(self):

        # impersonate="chrome" reproduces the TLS fingerprint of a real Chrome browser:

        # TikTok often rejects plain requests at this stage.

        self.session = cffi_requests.Session(impersonate="chrome")

        try:  # get initial cookies, like a regular browser

            self.session.get("https://www.tiktok.com/", headers=HEADERS,

                             proxies=self.proxies, timeout=self.timeout)

        except Exception:

            pass

 

    def current_ip(self):

        r = self.session.get(IP_CHECK_URL, proxies=self.proxies, timeout=self.timeout)

        return r.json().get("ip")

 

    def change_ip(self):

        if not self.change_ip_url:

            return

        try:

            # The IP rotation link is called directly, not via the proxy.

            cffi_requests.get(self.change_ip_url, timeout=self.timeout)

            log("  IP changed via link, waiting 5 sec.")

        except Exception as exc:

            log(f"  Failed to call the IP rotation link: {exc}")

        time.sleep(5)

        self._new_session()

 

    def pause(self):

        time.sleep(random.uniform(self.delay * 0.5, self.delay * 1.5))

 

    def save_debug(self, html):

        os.makedirs("debug", exist_ok=True)

        self.debug_counter += 1

        path = os.path.join("debug", f"page_{self.debug_counter}.html")

        with open(path, "w", encoding="utf-8") as fh:

            fh.write(html)

        return path

 

    def fetch(self, url, parser):

        for attempt in range(1, self.retries + 1):

            html = None

            try:

                r = self.session.get(url, headers=HEADERS, proxies=self.proxies,

                                     timeout=self.timeout, allow_redirects=True)

                html = r.text

                if r.status_code in (403, 429) or r.status_code >= 500:

                    raise NoDataError(f"HTTP {r.status_code}")

                return parser(html)

            except Exception as exc:

                note = ""

                if html and attempt == self.retries:

                    note = f", HTML saved to {self.save_debug(html)}"

                log(f"  attempt {attempt}/{self.retries}: {exc}{note}")

                if attempt < self.retries:

                    self.change_ip()

                    time.sleep(2 ** attempt)

        return None



# ---------------------------------------------------------------------------

# Input, output, entry point

# ---------------------------------------------------------------------------

 

def log(message):

    print(message, flush=True)



def read_list(value):

    if not value:

        return []

    if os.path.isfile(value):

        with open(value, encoding="utf-8") as fh:

            items = [line.strip() for line in fh]

    else:

        items = [part.strip() for part in value.split(",")]

    return [item for item in items if item and not item.startswith("#")]



def write_csv(path, rows, sep=";"):

    if not rows:

        return

    # utf-8-sig and the ";" delimiter – so that Excel with many European regional settings splits the data into columns right away

    with open(path, "w", newline="", encoding="utf-8-sig") as fh:

        writer = csv.DictWriter(fh, fieldnames=list(rows[0].keys()), delimiter=sep)

        writer.writeheader()

        writer.writerows(rows)



def main():

    parser = argparse.ArgumentParser(description="Simple scraper for public TikTok data via a proxy")

    parser.add_argument("--proxy", default=os.environ.get("TT_PROXY"),

                        help="http://LOGIN:PASSWORD@HOST:PORT (or the TT_PROXY variable)")

    parser.add_argument("--videos", help="file with video URLs or a comma-separated list")

    parser.add_argument("--users", help="file with usernames or a comma-separated list")

    parser.add_argument("--change-ip-url", help="IP rotation link for the port (optional)")

    parser.add_argument("--delay", type=float, default=4.0, help="average pause between requests, sec")

    parser.add_argument("--retries", type=int, default=3, help="attempts per page")

    parser.add_argument("--timeout", type=int, default=30, help="request timeout, sec")

    parser.add_argument("--out", default="tiktok_result", help="output file prefix")

    parser.add_argument("--sep", default=";", help="CSV delimiter: \";\" for European-locale Excel, \",\" for US/UK")

    args = parser.parse_args()

 

    videos, users = read_list(args.videos), read_list(args.users)

    if not videos and not users:

        parser.error("specify --videos and/or --users")

    if not args.proxy:

        log("Warning: no proxy set, requests will be sent from your own IP.")

 

    fetcher = Fetcher(args.proxy, args.change_ip_url, args.delay, args.retries, args.timeout)

 

    try:

        log(f"External IP: {fetcher.current_ip()}")

    except Exception as exc:

        sys.exit(f"Proxy is not responding: {exc}\nCheck the host, port, login, password and protocol.")

 

    video_rows, user_rows, failed = [], [], []

 

    for i, url in enumerate(videos, 1):

        log(f"[video {i}/{len(videos)}] {url}")

        row = fetcher.fetch(url, parse_video)

        if row:

            row["url"] = url

            video_rows.append(row)

            log(f"  ok: {row['views']} views, {row['likes']} likes")

        else:

            failed.append(url)

        fetcher.pause()

 

    for i, name in enumerate(users, 1):

        name = name.lstrip("@")

        url = f"https://www.tiktok.com/@{name}"

        log(f"[profile {i}/{len(users)}] @{name}")

        row = fetcher.fetch(url, parse_user)

        if row:

            row["url"] = url

            user_rows.append(row)

            log(f"  ok: {row['followers']} followers, {row['videos']} videos")

        else:

            failed.append(url)

        fetcher.pause()

 

    files = []

    for suffix, rows in (("_videos.csv", video_rows), ("_users.csv", user_rows)):

        if rows:

            write_csv(args.out + suffix, rows, args.sep)

            files.append(args.out + suffix)

    with open(f"{args.out}.json", "w", encoding="utf-8") as fh:

        json.dump({"videos": video_rows, "users": user_rows, "failed": failed},

                  fh, ensure_ascii=False, indent=2)

    files.append(f"{args.out}.json")

 

    log(f"\nDone: videos {len(video_rows)}, profiles {len(user_rows)}, failed {len(failed)}.")

    log("Files: " + ", ".join(files))



if __name__ == "__main__":

    main()

Back to home
Share
Contact Support
for an instant proxy test