twscrape is an async Python library and CLI for X/Twitter Search and GraphQL endpoints. It runs on your own account pool, keeps sessions in SQLite, rotates accounts when an endpoint is rate-limited, and returns either parsed SNScrape-style models or raw API responses.
Install
pip install twscrape
twscrape uses curl-cffi by default, with a browser-like TLS fingerprint that Cloudflare requires on some operations, for example user_by_id. If something breaks, TWS_HTTP_BACKEND=httpx switches back to httpx.
Features
Search and GraphQL X/Twitter API methods
Async/await API for running multiple scrapers concurrently
Login flow with optional email verification code retrieval
Cookie-based account setup
Saved account sessions and per-account proxies
Raw Twitter API responses and parsed SNScrape-compatible models
Automatic account switching across rate-limited operations
Sponsor
Proxy-Seller provides residential, ISP, IPv4 and IPv6 proxies in 220+ locations, from $0.70 per GB, with 24/7 support.
Promo code TWSCRAPE gives 15% off ISP, IPv4 and residential proxies.
Start With Cookies
twscrape requires authorized X/Twitter accounts. The most stable setup is to add an account from browser cookies containing auth_token and ct0. The recommended way to export them from your current browser profile is unjar:
my_account is a local identifier; twscrape does not verify that it matches the X username stored in the cookies. Run the same command again to replace its saved session while preserving credentials, statistics, locks, and proxy settings.
Alternatively, let the CLI prompt securely for cookies copied from x.com -> DevTools (F12) -> Application -> Cookies:
twscrape add_cookie my_account
Cookie accounts that include auth_token and ct0 are activated immediately; no login_accounts step is needed.
Ready-to-use cookie accounts are available from this provider. Proxy users can bring their own proxies or use Proxy-Seller. These are referral links.
X/Twitter's Terms of Service discourage using multiple accounts. Use this project responsibly and at your own discretion.
Python API
import asyncio
from twscrape import API, gather
async def main():
api = API() # or API("accounts.db")
# Add once; the session is stored in the account database.
await api.pool.add_account_cookies("my_account", "auth_token=xxx; ct0=yyy")
user = await api.user_by_login("xdevelopers")
print(user.id, user.username, user.followersCount)
tweets = await gather(api.search("from:xdevelopers lang:en", limit=20))
for tweet in tweets:
print(tweet.id, tweet.user.username, tweet.rawContent)
if __name__ == "__main__":
asyncio.run(main())
gather() is a convenience helper. You can stream results directly:
async for tweet in api.search("open source lang:en", limit=100):
print(tweet.id, tweet.rawContent)
Configure what happens when no account is immediately available:
api = API(raise_when_no_account=True, wait_timeout=30, wait_interval=1)
wait_timeout limits how long to wait for a locked account, wait_interval controls how often the pool checks again, and raise_when_no_account raises NoAccountError instead of ending the operation. By default, twscrape waits indefinitely while active accounts are locked.
X sometimes sends a tweet without its author's profile. The tweet is still returned, with a placeholder tweet.user (the same goes for retweeted and quoted tweets): only id is known, plus username and sometimes displayname when the referencing tweet names the author. Its counts are 0, created is the Unix epoch and profileImageUrl is empty, which never happens for a real profile, so check tweet.user.profileImageUrl == "" before storing user stats.
Search defaults to the Latest tab. Pass kv={"product": "Top"} or kv={"product": "Media"} to use another search product:
Parsed Tweet, User, Community, and trend objects can be converted with .dict() or .json().
Errors
A failed request raises instead of looking like an empty result:
AbortReqError when twscrape gives up on a request, for example on an HTML block page, including GqlFeaturesOutdatedError when X requires GraphQL features twscrape can't enable
ApiError, its subclass, when X answers with errors and no data; a busy or timed-out X (LoadShed, DeadlineExceeded) is retried a few times first
XClIdParseError when the X client transaction ID can't be generated
ParseError when tweet_details(), user_about() or community_info() gets the requested object but twscrape can't parse it; its subclass UserParseError for user_by_id() and user_by_login()
A paginated method raises on the page that failed, after yielding the earlier pages, and skips single items it can't parse. None from tweet_details(), user_by_id(), user_by_login(), user_about() or community_info() means X has no such object (or no account was available and raise_when_no_account is off). In the CLI, a failed request exits with code 1 without a traceback.
twscrape login_accounts starts the login flow for each inactive account. If X asks for email verification and email_password is available, twscrape tries to read the code through IMAP and saves the resulting cookies for later use.
line_format describes how each line is split. Supported tokens:
username - required
password - required
email - required
email_password - used to fetch email verification codes through IMAP
cookies - cookie string, JSON, base64, or another format accepted by the parser
limit is the target number of parsed objects, not a page size. X/Twitter controls page size per endpoint, so a call can return fewer or more objects than requested.
Rate limits are tracked per account and per endpoint. When an account is limited for one operation, twscrape locks it for that operation until the reset time and tries another active account.
user_tweets and user_tweets_and_replies are limited by X/Twitter to about 3200 tweets.
Proxy
Use a proxy per account, per API instance, or for CLI commands:
twscrape collects anonymous, aggregated telemetry about used GraphQL operation names and the selected HTTP backend. It does not collect usernames, cookies, proxies, queries, request URLs, or response bodies. Disable it with TWS_TELEMETRY=0.