Metadata-Version: 2.4
Name: xscrape
Version: 0.1.1
Summary: Scrape x.com (Twitter) with your browser session: search, profiles, timelines, followers, media downloads.
Keywords: twitter,x,scraper,twitter-scraper,graphql,osint,cli,asyncio,media-downloader
Author: Antoine Paix
License-Expression: MIT
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Utilities
Classifier: Typing :: Typed
Requires-Dist: aiofiles>=25.1
Requires-Dist: aiosqlite>=0.20
Requires-Dist: beautifulsoup4>=4.12
Requires-Dist: browser-cookie3>=0.20
Requires-Dist: curl-cffi>=0.17
Requires-Dist: pydantic>=2.7
Requires-Dist: rich>=13
Requires-Dist: typer>=0.12
Requires-Dist: xclienttransaction>=1.0.3
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/AntoinePaix/xscrape
Project-URL: Repository, https://github.com/AntoinePaix/xscrape
Project-URL: Issues, https://github.com/AntoinePaix/xscrape/issues
Description-Content-Type: text/markdown

# xscrape

[![CI](https://github.com/AntoinePaix/xscrape/actions/workflows/ci.yml/badge.svg)](https://github.com/AntoinePaix/xscrape/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/xscrape)](https://pypi.org/project/xscrape/)
[![Python](https://img.shields.io/pypi/pyversions/xscrape)](https://pypi.org/project/xscrape/)

`xscrape` is a Python package and command-line tool that scrapes tweets and profiles from the x.com (Twitter) web
app, with the session of your browser.

- No API key: it calls the same GraphQL API as x.com's web app (`/i/api/graphql`), with your session cookies
- Requests with [curl_cffi](https://github.com/lexiforest/curl_cffi), impersonating a real browser's TLS fingerprint
- Signs each call with an `x-client-transaction-id` header, like the web app (x.com refuses searches without it)
- The GraphQL operations (query ids, feature flags) are built in, and can be refreshed from requests copied out of
  the browser, so a new x.com release needs no code change
- Waits for the end of the rate-limit window on HTTP 429; retries on network errors and 5xx
- HTTP(S) and SOCKS proxies with failover
- Downloads photos, videos and GIFs in parallel (an `asyncio` queue of workers, files written with `aiofiles`)
- Every account seen is remembered in a local SQLite cache (`aiosqlite`), which saves a profile request per command
- Command `xscrape`, or `python -m xscrape`, or use it as a library

Requires Python 3.11 or later.

> **Status:** search (tweets, people, lists), profiles and their "About this account" panel, the tabs of a profile
> (posts, replies, reposts, media), followers and following, single tweets and their replies, the tweets of a list, and
> media downloads work.

## Installation

Pick one of the options below. They all install the `xscrape` command.

### With uv

```bash
# As a tool, available everywhere:
uv tool install xscrape

# The latest version from GitHub:
uv tool install git+https://github.com/AntoinePaix/xscrape

# Or from a clone (runs from the project's own virtual environment):
git clone https://github.com/AntoinePaix/xscrape
cd xscrape
uv sync
uv run xscrape --help
```

### With pip

```bash
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install xscrape
```

## Usage

### Configuration

xscrape needs a logged-in x.com session: the `auth_token` and `ct0` cookies. It takes them, in this order:

1. from `XSCRAPE_COOKIES`, in the environment or a `.env` file (`$XSCRAPE_ENV_FILE`, `./.env`, then
   `~/.config/xscrape/.env`);
2. otherwise from the cookies of your browser (`--browser`): by default Chrome, then Firefox if Chrome cannot be read
   or is not logged in to x.com.

The simplest way to fill the `.env` file: in the browser, open the developer tools on x.com, find a request to
`/i/api/graphql/…` in the Network tab (for example `SearchTimeline` while searching), *Copy as cURL (POSIX)*, save
it to a file and run:

```bash
xscrape config import-curl request.curl   # session -> ./.env, GraphQL operation -> ~/.config/xscrape/operations.json
xscrape config show                       # where the session comes from, known operations (no secret shown)
```

| Variable | Description |
| --- | --- |
| `XSCRAPE_COOKIES` | Cookies of the session, as `name=value; name2=value2` (`auth_token` and `ct0` at least) |
| `XSCRAPE_BEARER` | Bearer token of the web app; without it, it is read from x.com's main script |
| `XSCRAPE_USER_AGENT` | User agent sent with the requests; default: the impersonated browser's |
| `XSCRAPE_ENV_FILE` | Path of a `.env` file to load first |
| `XSCRAPE_CACHE_DIR` | Folder of the cache: the users database and x.com's `ondemand.s` script (default `~/.cache/xscrape`) |

The browser cookies are read with [browser-cookie3](https://github.com/borisbabic/browser_cookie3). Chrome and the
browsers built on it encrypt their cookies: on Linux the key is in the keyring of your session (GNOME Keyring,
KWallet), which must be unlocked; on Windows, recent Chrome versions cannot be read, and `auto` then falls back to
Firefox. When `auto` falls back, it says why Chrome was not used. A browser named with `--browser` is the only one
read. To use the browser after an import, remove the `XSCRAPE_COOKIES` line from `.env`: it always comes first.

Real environment variables take precedence over the `.env` file. **Never commit `.env` or `*.curl` files**: they
hold your session. They are listed in `.gitignore`, the pre-commit hooks refuse them, and `pyproject.toml` leaves
them out of the built package, so captures can be kept anywhere in the clone (for example `src/xscrape/curl_requests/`).

### Commands

| Command | Description |
| --- | --- |
| `xscrape search QUERY [-p TAB] [-n LIMIT] [-o FILE]` | Search tweets, people or lists; print them as JSON Lines |
| `xscrape user USERNAME... [-i FILE] [-o FILE]` | Show the profile of an account as JSON, of several as JSON Lines |
| `xscrape about USERNAME [-o FILE]` | Show the "About this account" panel: country, creation source, username changes |
| `xscrape tweets USERNAME [-t TAB] [-n LIMIT] [-o FILE]` | Print the tweets of an account as JSON Lines, newest first |
| `xscrape followers USERNAME [--verified] [-n LIMIT] [-o FILE]` | Print the followers of an account as JSON Lines |
| `xscrape following USERNAME [-n LIMIT] [-o FILE]` | Print the accounts an account follows as JSON Lines |
| `xscrape tweet TWEET... [-i FILE] [-o FILE]` | Show a tweet (id or URL) as JSON, several as JSON Lines |
| `xscrape replies TWEET [--sort ORDER] [-n LIMIT] [-o FILE]` | Print the replies to a tweet as JSON Lines |
| `xscrape retweeters TWEET [-n LIMIT] [-o FILE]` | Print the accounts that retweeted a tweet as JSON Lines |
| `xscrape list-tweets LIST [-n LIMIT] [-o FILE]` | Print the tweets of a list (id or URL) as JSON Lines |
| `xscrape download USERNAME [-t TAB] [-n LIMIT] [-d DIR] [-c N]` | Download the photos, videos and GIFs of an account |
| `xscrape download --search QUERY [-p TAB] [-n LIMIT] [-d DIR] [-c N]` | Download the photos, videos and GIFs of search results |
| `xscrape download --list LIST [-n LIMIT] [-d DIR] [-c N]` | Download the photos, videos and GIFs of the tweets of a list |
| `xscrape download --tweet TWEET [-d DIR]` | Download the photos, videos and GIFs of one tweet |
| `xscrape cache users [-s TEXT] [-n LIMIT] [-o FILE]` | List the accounts remembered in the cache |
| `xscrape cache stats` / `clear [-y]` | Cache location, number of users and age of the saved `ondemand.s` / empty the cache |
| `xscrape raw OPERATION [-V JSON] [-o FILE]` | Call an imported GraphQL operation and print its raw JSON answer |
| `xscrape config import-curl FILE` | Save the session and the GraphQL operation of a request copied as cURL |
| `xscrape config show` | Show where the session comes from and the known operations |

```bash
xscrape search "python lang:en" -n 200 -o python.jsonl       # latest tweets, one JSON object per line
xscrape search "from:NASA filter:media" -p top -n 50         # x.com's search syntax: from:, since:, until:, lang:...
xscrape search "data science" -p people -n 40                # accounts
xscrape search python -p lists                               # lists
xscrape user @NASA                                           # profile (also: NASA, https://x.com/NASA)
xscrape user id:11348282                                     # profile by user id (also: https://x.com/i/user/11348282)
xscrape user NASA X id:11348282 -o accounts.jsonl            # several profiles: one request per 100
xscrape user -i usernames.txt -o accounts.jsonl              # one username or id per line
xscrape about X                                              # country, source, username changes, verified since
xscrape tweets NASA -n 500 -o nasa.jsonl                     # tweets of an account
xscrape tweets NASA -t replies -n 50                         # its replies (also: reposts, media)
xscrape following NASA -n 500 -o nasa_following.jsonl       # the accounts it follows
xscrape followers NASA --verified -n 200                     # its followers with a verified account
xscrape tweet https://x.com/NASA/status/2124903027370774900 # one tweet
xscrape tweet -i tweet_ids.txt -o tweets.jsonl               # many tweets: one request per 100 ids
jq -r .reply_to tweets.jsonl | grep -v null | xscrape tweet -i - # the tweets they answer, from standard input
xscrape replies 2124903027370774900 --sort recent -n 200     # its replies, newest first
xscrape retweeters 2124903027370774900 -n 1000               # the accounts that retweeted it
xscrape list-tweets https://x.com/i/lists/<id> -n 300        # the tweets of a list (find lists with search -p lists)
xscrape download NASA -n 100                                 # its last 100 posts with media -> downloads/NASA/
xscrape download NASA -t reposts -d ~/x -c 8                 # media of what it retweeted, 8 files at a time
xscrape download --search "from:NASA filter:media" -n 50     # media of 50 search results -> downloads/search/from_NASA_filter_media/
xscrape download -s "#Artemis since:2026-11-01" -p latest    # every result with media, newest first
xscrape raw SearchTimeline                                   # with the variables of the imported request
xscrape raw SearchTimeline -V '{"rawQuery":"python","count":20,"querySource":"typed_query","product":"Latest"}' -o search.json
```

`USERNAME` is a username (`NASA`, `@NASA`, `https://x.com/NASA`) or a user id, written `id:11348282` or
`https://x.com/i/user/11348282` (`UserByRestId`), in every command that takes one: `user`, `about`, `tweets`,
`followers`, `following` and `download`. A bare number is a username: x.com usernames can be all digits. An id keeps
working after the account changes its username.

From a clone installed with `uv sync`, prefix the commands with `uv run`. The exit code is `1` on an error, `2` on a
usage error and `130` on Ctrl-C.

### Common options

Same options, with the same names, as in the other scraper repos:

| Option | Default | Description |
| --- | --- | --- |
| `-o`, `--output` | | File to write the results to, instead of the terminal |
| `-x`, `--proxy` | | Proxy to use; repeat for several (see [Proxies](#proxies)) |
| `--proxy-file` | | File with one proxy per line |
| `--impersonate` | `chrome` | curl_cffi browser fingerprint |
| `--timeout` | `30` | Timeout of each request, in seconds |
| `--retries` | `3` | Retries per request on network errors or 5xx responses |
| `-v`, `--verbose` | | Show debug logs (each request) |
| `-q`, `--quiet` | | Only show warnings and errors |
| `--version` | | Show the version and exit |

Options specific to xscrape:

| Option | Default | Description |
| --- | --- | --- |
| `--browser` | `auto` | Browser whose x.com cookies are used when `XSCRAPE_COOKIES` is not set: `auto` (Chrome, then Firefox), `chrome`, `firefox`, `chromium`, `brave`, `edge`, `opera`, `vivaldi`, `librewolf` or `safari` |
| `--wait / --no-wait` | `--wait` | On HTTP 429, wait for the end of the rate-limit window, or stop |
| `-p`, `--product` | `latest` | `search`: tab of the search page: `top`, `latest`, `media` (tweets), `people` or `lists`; `download --search`: `top`, `latest` or `media` (default) |
| `-n`, `--limit` | `100` | `search`, `tweets`, `followers`, `following`, `replies`, `retweeters`, `list-tweets`: maximum number of results; `download`: of tweets with media (default: all) |
| `--verified` | | `followers`: only the followers with a verified account (`BlueVerifiedFollowers`) |
| `-i`, `--input` | | `tweet`, `user`: file with one id, URL or username per line (`#` comments ignored), `-` for standard input |
| `--sort` | `relevance` | `replies`: order of the replies, `relevance` (x.com's choice), `recent` or `likes` |
| `-l`, `--list` | | `download`: download from the tweets of this list (id or URL) |
| `--tweet` | | `download`: download the files of this one tweet (id or URL) |
| `-t`, `--tab` | `posts` | `tweets`, `download`: tab of the profile, `posts`, `replies`, `reposts` or `media` |
| `-d`, `--dir` | `downloads` | `download`: root folder; the files go to `DIR/USERNAME/`, `DIR/search/QUERY/` or `DIR/list/LIST_ID/` |
| `-c`, `--concurrency` | `4` | `download`: files downloaded at the same time |
| `--overwrite` | | `download`: download again the files that exist (they are skipped otherwise) |
| `-s`, `--search` | | `download`: download from the results of this search instead of an account; `cache users`: only the users whose username or name contains this |
| `-V`, `--variables JSON` | the imported ones | `raw`: variables of the call |

## Proxies

```bash
xscrape raw SearchTimeline -x socks5h://user:pass@proxy.example:1080
xscrape raw SearchTimeline --proxy-file proxies.txt
```

- **Formats**: `scheme://[user:pass@]host:port` (`http`, `https`, `socks4`, `socks4a`, `socks5`, `socks5h`),
  `host:port`, or `host:port:user:pass`. The two short forms are treated as HTTP proxies.
- **Proxy file**: one proxy per line. Blank lines and `#` comments are ignored.
- **Environment variables**: `XSCRAPE_PROXY` (space-separated list) and `XSCRAPE_PROXY_FILE` set the same options as
  `--proxy` and `--proxy-file`. Without any proxy option, curl's own `HTTPS_PROXY` and `ALL_PROXY` variables still
  apply.
- **Rotation**: a logged-in session that changes address on every request looks suspicious, so the first working
  proxy is kept (`sticky` rotation). The next one is only used after a failure.
- **Failures**: if a request fails through a proxy (network error), the retry goes through a different proxy after
  a short pause. A proxy that fails 3 times in a row is skipped for 60 seconds. If every proxy is being skipped,
  they are all used anyway.
- **Logs**: proxy passwords are shown as `***`.

## Output

`search` prints one tweet per line (JSON Lines), or writes them to `-o FILE`. Each line is a `Tweet` of
`src/xscrape/models.py`, without its empty fields:

```json
{"id": "2124903027370774900", "author": {"id": "11348282", "username": "NASA", "name": "NASA", "followers": 92134873, …},
 "text": "…", "created_at": "2026-11-23T16:28:55Z", "lang": "en", "replies": 120, "retweets": 450, "likes": 3100,
 "views": 250000, "media": [{"kind": "video", "url": "https://video.twimg.com/….mp4", …}],
 "hashtags": [], "mentions": [], "urls": [], "reply_to": "…", "quoted": {…}, "retweeted": {…}}
```

Long tweets have their whole text (not cut at 280 characters), videos and GIFs the URL of their best MP4. `views`
is missing while x.com does not show a count yet. With `-p people` each line is a `User`, with `-p lists` a
`TwitterList` (`id`, `name`, `description`, `created_at`, `members`, `subscribers`, `private`, `owner`). `raw`
prints the `data` of the GraphQL answer as JSON.

`user` prints one `User`: `id`, `username`, `name`, `description`, `created_at`, `followers`, `following`, `tweets`,
`verified`, `protected`, `location`, `website` (the real address, not its t.co link), `avatar` (full size) and
`banner`.

`about` prints the "About this account" panel of a profile (`AboutAccountQuery`), with the account under `user`:

```json
{"user": {"id": "783214", "username": "X", "name": "X", "created_at": "2007-02-20T14:35:54Z", "verified": true, …},
 "country": "United States", "country_accurate": true, "location_accurate": true, "source": "Web",
 "username_changes": 2, "last_username_change": "2023-07-26T02:56:42.387000Z", "verified_type": "Business",
 "verified_since": "2013-03-07T23:57:12.470000Z", "identity_verified": false}
```

| Field | Meaning |
| --- | --- |
| `country` | the country the account is based in, as x.com shows it (missing for some accounts, e.g. NASA) |
| `country_accurate`, `location_accurate` | x.com's own flags on that country and on the location |
| `source` | how the account was created or connected: `Web`, `United States App Store`… |
| `affiliate` | the account it is affiliated with (`@Space_Station` → `NASA`) |
| `username_changes`, `last_username_change` | how many times the username changed, and when last |
| `verified_type`, `verified_since`, `identity_verified` | `Government`, `Business` or none; since when; ID verified |

A field x.com does not send for an account is left out. The answer has no bio, location or counts: use `user` for
those.

`tweets` gives a tab of the profile page, always limited to the account's own tweets:

| Tab | Operation | Content |
| --- | --- | --- |
| `posts` | `UserOriginalsTimeline` | the pinned tweet, then its tweets and own threads; no retweets |
| `replies` | `UserRepliesTimeline` | its tweets and replies to anyone (`reply_to` is the id of the answered tweet; the answered tweets themselves are left out) |
| `reposts` | `UserRepostsTimeline` | its retweets (`retweeted` holds the original tweet) |
| `media` | `UserVideoTimeline` | its tweets with photos, videos or GIFs |

`followers` and `following` print one `User` per line, most recent first: the followers of an account (`Followers`,
or `BlueVerifiedFollowers` with `--verified`) or the accounts it follows (`Following`). x.com sends about 50 to 70
accounts per page; suspended accounts are left out, so a list can be a little shorter than the count of the profile.
The lists of a protected account are only visible to its followers.

`tweet` prints one `Tweet` (`TweetResultByRestId`). `replies` prints the replies to a tweet as the page of the tweet
shows them (`TweetDetail`): each reply, followed by the answers to it, in the order of `--sort`; the tweet itself, and
the tweets it answers when it is a reply, are left out. `list-tweets` prints the tweets of the members of a list, newest
first, with the tweets they answer in context (`ListLatestTweetsTimeline`); a private list is only visible to its owner
and followers. `retweeters` prints the accounts that retweeted a tweet, one `User` per line (`Retweeters`): x.com lists
most of them, not all (893 accounts for a NASA tweet with 1,012 retweets). `TWEET` is an id or a URL
(`https://x.com/NASA/status/2124903027370774900`), `LIST` an id or a URL (`https://x.com/i/lists/<id>`). A deleted or
hidden tweet, and a list that x.com does not show, are an error (exit code `1`).

`tweet` and `user` take several values at once, as arguments or with `-i FILE`, and fetch them 100 per request:
`TweetResultsByRestIds` for tweets, `UsersByScreenNames` for usernames and `UsersByRestIds` for user ids (a
mix of usernames and ids costs two requests per 100). x.com answered 250 tweets in one request; 100 keeps the URLs
short. The results are written as JSON Lines, in the order given, each value once; the values x.com does not return
(deleted, suspended or hidden) are listed in a warning, and the exit code is then `1`. With a single value and no
`-i`, the output stays one pretty-printed JSON object. These three operations are not captured from the web app:
they are declared in its main script (`abs.twimg.com/responsive-web/client-web/main.<hash>.js`, which lists the
query id and the feature flags of every operation), with the flag values of the captured operations.

`ListSearchTimeline` (the search box of the Lists page) is built in too, for `raw`; it gives the same lists as
`search -p lists`.

### Downloads

`download` takes the tweets of a profile tab (`posts` by default: the pinned tweet, then the account's tweets and
threads, without retweets), of a search with `--search` (the `media` tab of the search page by default, `-p top` or `-p
latest` otherwise), of a list with `--list`, or one tweet with `--tweet`, and downloads every photo (original size),
video (best MP4) and GIF (as MP4) of the tweets that have some. The files of an account, and of one tweet, go to
`DIR/USERNAME/`, those of a list to `DIR/list/LIST_ID/`, those of a search to `DIR/search/QUERY/`, where `QUERY` is the
query with its spaces and punctuation turned into `_` (`from:NASA filter:media` gives `from_NASA_filter_media`). They
are named `<date>_<tweet id>_<n>.<ext>`, e.g. `20261123_2124903027370774900_1.mp4`; the tweet is
`https://x.com/i/status/<tweet id>`. `-n` counts tweets with media, not files (a tweet can hold up to 4 photos) nor the
tweets without media, which are passed over. A retweet gives the files of the original tweet. Pages of tweets are
fetched as the downloads progress (a bounded `asyncio.Queue` between the timeline and `-c` workers); each file is
written to `NAME.part`, checked against its announced size and renamed, so an interrupted run leaves no half-written
file under its final name, and the next run skips what is already there. The files are fetched with the same browser
fingerprint and proxies as the API calls. The exit code is `1` if a file failed.

x.com sends an empty media tab for the accounts it marks as sensitive (their profile opens with a "may include
sensitive content" warning); `-t media` then takes the media of the posts tab instead, with a warning. The default
`posts` tab is not affected.

```bash
xscrape download NASA                                        # every post with media -> downloads/NASA/
xscrape download NASA -n 200 -c 8                            # its last 200 posts with media, 8 downloads at a time
xscrape download NASA -t replies -n 50                       # media of its tweets and replies
xscrape download NASA -t media                               # its media tab instead
xscrape download --search "from:NASA filter:videos" -n 20    # 20 search results with videos
xscrape download -s "eclipse filter:images" -p top -d ~/x   # top results -> ~/x/search/eclipse_filter_images/
xscrape download -s "from:NASA" -p latest -n 100 --overwrite # download again what already exists
xscrape download --tweet https://x.com/NASA/status/2124903027370774900   # one tweet -> downloads/NASA/
xscrape download --list https://x.com/i/lists/<id> -n 50     # 50 tweets of a list -> downloads/list/<id>/
```

### Cache

Every command stores the accounts it sees in `~/.cache/xscrape/cache.db` (SQLite, `XSCRAPE_CACHE_DIR` to move it): the
authors of tweets, of quoted and retweeted tweets, accounts found by search, followers and followed accounts, list
owners and profiles. The `users`
table has the columns of `User` (`user_id`, `username`, `name`, `followers`…) plus `first_seen` and `last_seen`; a
value that a sighting does not give never erases a known one.

`tweets`, `followers`, `following` and `download` look the username (or the user id) up in the cache first, and
only call `UserByScreenName` (or `UserByRestId`) for an account never seen. `user` always fetches the profile (and
updates the cache). An account that changed its username is found under its new name once seen again, and always
by its id; if an old name points to the wrong account, run `xscrape cache clear`.

The same folder keeps x.com's `ondemand.s` script, needed for the transaction ids (see
[How it works](#how-it-works)), in `ondemand/`. A run reuses the saved copy for 24 hours, then downloads it again;
it also downloads it again as soon as x.com names a new script, when the saved copy is unusable, and on the retry
after a `404`. Only the newest script is kept. Nothing breaks if the folder is missing or read-only: the script is
then downloaded on every run, as without a cache.

```bash
xscrape cache stats                        # users, and the saved ondemand.s with its age
xscrape cache users -s nasa -n 20          # table in the terminal
xscrape cache users -o users.jsonl         # export every cached account
xscrape cache clear -y                     # delete the users and the saved ondemand.s
```

## Library use

```python
import asyncio

from xscrape import Settings
from xscrape import XClient
from xscrape import search


async def main():
    async with XClient(Settings.load()) as client:  # XSCRAPE_COOKIES, else Chrome, then Firefox
        async for tweet in search(client, "python lang:en", product="Latest", limit=50):
            print(tweet.created_at, tweet.author.username, tweet.text[:80])


asyncio.run(main())
```

`search_users` and `search_lists` work the same way for the People and Lists tabs, `user_tweets(client, "NASA",
tab="media")` for the tweets of an account, `followers(client, "NASA", verified=False)` and `following(client, "NASA")`
for its accounts, `tweet_replies(client, tweet, sort="Recency")` and `tweet_retweeters(client, tweet)` for the replies
to a tweet and its retweeters and `list_tweets(client, list)` for the tweets of a list; `await get_user(client, "NASA")`
returns a profile, `get_users(client, ["NASA", "id:783214"])` and `get_tweets(client, ids)` yield `(value, result or
None)` pairs in batches of 100, `await get_about(client, "NASA")` its "About this account" panel and `await
get_tweet(client, tweet)` a tweet. With a cache:

```python
from xscrape import Cache
from xscrape import Downloader
from xscrape import jobs_from
from xscrape import resolve_user
from xscrape import user_tweets
from xscrape import with_media
from xscrape.config import cache_path

async with XClient(Settings.load()) as client, Cache(cache_path()) as cache:
    user = await resolve_user(client, "NASA", cache)  # cache first, then x.com
    tweets = with_media(user_tweets(client, user, tab="posts"), limit=50)  # its last 50 posts with media
    stats = await Downloader(client, concurrency=4).run(jobs_from(tweets, Path("downloads/NASA")))
```

`with_media(tweets, limit)` keeps the tweets that have files, and `user_media(client, user, limit=…)` reads the media
tab with the fallback above. `jobs_from` takes any async iterator of tweets, so the media of search results download
the same way:

```python
from xscrape import folder_name

async with XClient(Settings.load()) as client:
    query = "from:NASA filter:media"
    tweets = search(client, query, product="media", limit=50)
    stats = await Downloader(client).run(jobs_from(tweets, Path("downloads/search") / folder_name(query)))
    print(f"{stats.downloaded} files, {stats.bytes / 1e6:.1f} MB, {len(stats.failed)} failed")
```

`XClient.graphql(operation, variables)` calls any operation of `xscrape.operations`, and `parse_timeline`, `parse_tweet`,
`parse_user` and `parse_list` turn the answers into models. `XClient` accepts `impersonate`, `timeout`, `retries`,
`proxies` (a list of proxies or a `ProxyPool`), `wait_on_rate_limit`, `language`, `transaction_ids` and `ondemand_cache`
(an `OndemandCache(directory, max_age=86400)`, as the commands use with `xscrape.config.ondemand_dir()`; without it, the
script is downloaded once per client). Errors raise `xscrape.XError` subclasses (`ConfigError`, `AuthError`,
`NotFoundError`, `RateLimitError`). The library logs with the `logging` module under the `xscrape` logger.

## How it works

- **Session.** The web app authenticates its API calls with the `auth_token` cookie, the `ct0` cookie echoed in the
  `x-csrf-token` header, and the bearer token of the web app (a constant of its main script, read from
  `abs.twimg.com/responsive-web/client-web/main.<hash>.js` when `XSCRAPE_BEARER` is not set).
- **GraphQL.** Each call is `/i/api/graphql/<query id>/<operation>` with `variables`, `features` and sometimes
  `fieldToggles` as JSON: a GET query string, or a POST body. x.com changes the query ids and the feature flags with
  its releases, so `config import-curl` saves those of a captured request to `~/.config/xscrape/operations.json`, which
  overrides the built-in ones. A `404` or an error about features usually means it is time to import a fresh request.
- **Transaction id.** The web app signs each call with an `x-client-transaction-id` header, and x.com answers `404`
  to searches without a valid one (a value copied from the browser does not work either). It is computed from the
  method, the path, the time and keys of x.com's home page and `ondemand.s` script, by the
  [XClientTransaction](https://github.com/iSarabjitDhiman/XClientTransaction) library. xscrape fetches its inputs
  through its own session and proxies:
  - the home page, once per run: it holds the key and names the current `ondemand.s` script;
  - the `ondemand.s` script (`abs.twimg.com/responsive-web/client-web/ondemand.s.<hash>a.js`), from the cache when
    a copy less than 24 hours old is saved, else from x.com, then saved. Its URL names its content, so a copy stays
    valid until x.com ships another script; the 24-hour refresh is a safety net. This saves one request per run.

  The ids are then computed locally for each call. If a call still gets a `404` (a new x.com build changes the
  keys), xscrape downloads the home page and the script again, ignoring the saved copy, and tries the call once more.
- **Rate limits.** Each endpoint has a quota per 15-minute window. The answers give `x-rate-limit-remaining` and
  `x-rate-limit-reset`; on HTTP 429 the client waits until the reset (`--no-wait` to stop instead).

### Adding an operation

1. Capture a request of the web app that uses it and run `xscrape config import-curl FILE`.
2. Save a few answers with `xscrape raw NAME -V '…' -o tests/fixtures/NAME.json` (remove anything personal), then
   write the parser that turns them into `Tweet` / `User` models, tested offline against the fixtures.
3. Add the command in `cli.py`, and the operation to `BUILTIN` in `operations.py` if it should work without an
   import.

## Limitations

- A logged-in account is needed: x.com shows almost nothing to logged-out visitors.
- Timelines and searches end after a few hundred to a few thousand tweets, depending on the endpoint.
- Heavy use can get the account rate limited, locked or suspended. Keep the request rate reasonable and prefer a
  secondary account.
- This is unofficial and may break whenever x.com changes. Use it only for data you are allowed to collect, and
  respect X's Terms of Service and the privacy of the people whose posts you read.

## Development

The scraper repos (snapchat-cli, tiktok-scraper, vinted-api, scraping-classement-atout-france, tiktok-cli,
reddit-cli, ig-download, xscrape) share the same tooling: [uv](https://docs.astral.sh/uv/),
[ruff](https://docs.astral.sh/ruff/), [pytest](https://docs.pytest.org/), [pre-commit](https://pre-commit.com/) and
the same GitHub Actions pipeline.

```bash
uv sync --all-extras                # project + dev tools (pytest, ruff, pre-commit)
uv run pre-commit install           # once: run the hooks on every commit

uv run pytest                       # offline tests
uv run pytest -m live               # smoke tests against the real website
uv run ruff check --fix . && uv run ruff format .
uv run pre-commit run --all-files   # every hook, as the CI does
```

Without uv: `pip install -e . --group dev` (`--group` needs pip 25.1+), then run the same commands without
the `uv run` prefix.

- **Pre-commit hooks**: they block `.env` files, `.har` captures and `token.json` files, scan for secrets with
  gitleaks, refuse files over 1 MB, check YAML and TOML files, fix trailing whitespace and final newlines, run
  `ruff check --fix` and `ruff format`, and keep `uv.lock` in sync with `pyproject.toml`.
- **CI** (`.github/workflows/ci.yml`): on every push to `main` and every pull request, one job runs all the
  pre-commit hooks, and another runs the offline tests on Python 3.11, 3.12, 3.13 and 3.14.
- **Code style**: ruff with 120-character lines, one import per line and absolute imports only (see
  `pyproject.toml`).

This repo adds two hooks: captured `*.curl` requests are refused too, and so is any file holding an `auth_token=` or
`ct0=` cookie value. The live tests use your session and the imported operations, and are skipped without them.

### Releasing

Releases go to [PyPI](https://pypi.org/project/xscrape/) from GitHub Actions (`.github/workflows/release.yml`),
with PyPI's [Trusted Publishing](https://docs.pypi.org/trusted-publishers/): no token is stored anywhere.

Once, on PyPI (Account settings → Publishing → *Add a new pending publisher*): PyPI project name `xscrape`, owner
`AntoinePaix`, repository `xscrape`, workflow `release.yml`, environment `pypi`. On GitHub, the `pypi` environment
(Settings → Environments) can require an approval before each upload.

For each release:

```bash
# 1. set the version in pyproject.toml (e.g. 0.2.0), then:
uv lock
git commit -am "Release 0.2.0"
git tag v0.2.0
git push origin main v0.2.0     # the workflow checks the tag against the version, tests, builds and publishes
```

The workflow stops if the tag does not match the version of `pyproject.toml`, if a test fails, or if a package
holds a `.env`, `.har` or `.curl` file.

### Repository layout

```
.github/workflows/ci.yml   lint (pre-commit) + tests on Python 3.11 to 3.14
src/xscrape/
├── cli.py          # command line (typer): search, user, about, tweets, followers, following, tweet, replies,
│                   #   retweeters, list-tweets, download, cache, raw, config
├── client.py       # GraphQL client: curl_cffi, session headers, bearer token, retries, rate limits, proxies
├── transaction.py  # x-client-transaction-id header (XClientTransaction library), ondemand.s disk cache
├── timelines.py    # paging through a timeline by its cursor
├── search.py       # search: tweets, people, lists
├── users.py        # profiles, "About this account", the tabs of a profile, followers and following
├── tweets.py       # tweets by id, the replies to a tweet, its retweeters
├── lists.py        # the tweets of a list
├── cache.py        # SQLite cache of the accounts seen (aiosqlite)
├── downloader.py   # media downloads: asyncio queue of workers, aiofiles
├── parser.py       # GraphQL answers -> Tweet / User / Media
├── config.py       # settings: .env / environment / browser cookies
├── operations.py   # GraphQL operations: query ids, feature flags, operations.json
├── curl_import.py  # session and operation from a request copied as cURL
├── proxies.py      # proxy parsing, rotation and failover
├── models.py       # Tweet / User / Media / TwitterList / AccountAbout
└── errors.py       # error classes shown without a traceback
tests/              # pytest suite (fixtures: made-up answers in x.com's shape), live smoke tests
```

## License

[MIT](https://github.com/AntoinePaix/xscrape/blob/main/LICENSE)
