Frameworks
SocialCrawl in notebooks and pandas
Pull profiles and posts into a pandas DataFrame from Jupyter or Google Colab, with the next page one step away
Each block is one notebook cell. Saved together as socialcrawl-quickstart.py, they also open in VS Code as a notebook.
Prerequisites
- Python 3.11 or later.
- Jupyter, VS Code notebooks or Google Colab.
- A SocialCrawl API key. Keys start with
sc_.
Checking your account…
Set your API key
Install requests and pandas, and set your key in the shell before you start Jupyter. In Colab, add a Secret named SOCIALCRAWL_API_KEY instead.
pip install requests pandas
export SOCIALCRAWL_API_KEY=sc_your_key_hereNever paste the key into a cell, where anyone you share the notebook with would see it. The first cell reads it, and call sends it in the x-api-key header.
# %% Set your API key and the helper
import json
import os
import pandas as pd
import requests
try:
# Google Colab: the key is a Secret named SOCIALCRAWL_API_KEY.
from google.colab import userdata
os.environ["SOCIALCRAWL_API_KEY"] = userdata.get("SOCIALCRAWL_API_KEY")
except ImportError:
pass # Jupyter and VS Code read it from the shell that started them.
API = "https://www.socialcrawl.dev"
session = requests.Session()
session.headers["x-api-key"] = os.environ["SOCIALCRAWL_API_KEY"]
def call(path, **params):
"""Send one request. Raise with error.type and error.doc_url when success is false."""
body = session.get(API + path, params=params, timeout=60).json()
if not body["success"]:
error = body["error"]
raise RuntimeError(f"{error['type']}: {error['message']} ({error.get('doc_url')})")
return bodyGet a profile
The cell prints data.author.followers and shows the profile as a one-row table.
# %% Get a profile
profile = call("/v1/tiktok/profile", handle="charlidamelio")
print(f"followers: {profile['data']['author']['followers']} (credits_used {profile['credits_used']})")
pd.json_normalize(profile["data"]["author"])Every answer carries success, and call raises when it is false. Branch on error.type, never on the message text.
Many accounts into a table
Each profile is one call, and each author becomes one row of a DataFrame.
# %% Many accounts into a table
authors = [profile["data"]["author"]]
for handle in ["khaby.lame", "mrbeast"]:
authors.append(call("/v1/tiktok/profile", handle=handle)["data"]["author"])
accounts = pd.DataFrame(authors)
print(f"accounts: {len(accounts)} rows")
accounts[["username", "followers"]]Search across platforms
With dry_run=1 the search runs nothing and is free. data.estimate holds what the real search would cost and how many seconds it would take.
# %% Search across platforms
quote = call("/v1/search/everywhere", query="oat milk", format="compact", dry_run=1)
estimate = quote["data"]["estimate"]
print("estimate:", json.dumps({"credits": estimate["credits"], "seconds": estimate["seconds"]}))Drop dry_run to run the search for 20 credits.
Get posts and the next page
Each answer holds one page of posts in data.items. Send pagination.next_cursor back as cursor, and stop when pagination.has_more is false. Both pages land in one table.
# %% Get posts and the next page
params = {"handle": "charlidamelio"}
pages = []
for page in (1, 2):
posts = call("/v1/tiktok/profile/videos", **params)
pagination = posts["pagination"]
print(
f"page {page}: {len(posts['data']['items'])} posts "
f"(credits_used {posts['credits_used']}), next_cursor {pagination['next_cursor']}"
)
pages.append(pd.json_normalize(posts["data"]["items"]))
if not pagination["has_more"]:
break
params["cursor"] = pagination["next_cursor"]
videos = pd.concat(pages, ignore_index=True)
print(f"posts table: {len(videos)} rows")
videos.head()A page of posts costs 1 credit.
