To scrape twitter public posts with Python, start with the official X API: authenticate, submit a search query, follow pagination tokens and export deduplicated records. The API example below collects posts from the past seven days and exports JSONL; the alternative Twikit example uses an authenticated X account without an official API key.
This guide covers method selection, short Python examples, cleanup and a repeatable validation plan. The examples are against live X accounts; they demonstrate documented interfaces, not measured collection success.
Key Facts
- Prefer the official X API when its coverage and billing fit your public-data collection task.
- An HTTP 200 response alone does not establish that usable records were collected.
- Deduplicate collected posts by their stable post IDs.
- Keep missing engagement metrics distinct from zero values.
- Measure collection costs against unique usable records.
- A proxy cannot guarantee access or replace application authentication.
How to scrape twitter: choose your method
Choose the collection method around the public records you need, the authentication you can maintain and the cost you can accept. Prefer the official X API when it meets those requirements.

List the required fields, date range, available credentials and maximum cost per 1,000 usable posts. Compare the methods below against those requirements.
The Access framework: validate public-data scope, contractual permission and applicable law separately from session authentication.
X’s terms prohibit scraping without its express written permission, subject to applicable-law exceptions. Account credentials authenticate a session; they do not by themselves authorize scraping. Assess contractual permission and applicable law separately. Read our web scraping legal guide for additional context.
What data can you collect from Twitter (X)?
Define a public-data schema around post IDs, text, authors, timestamps and engagement counts. Treat each field as a requirement to validate, rather than assuming every response includes it.
- Identity: post ID, author ID and public username when available.
- Content: post text and public links relevant to the project.
- Time: publication timestamp and your collection timestamp.
- Engagement: available public counts, recorded with the collection time.
- Provenance: query, collection method and pagination checkpoint.
Keep IDs as strings. Preserve original text and timestamps before producing analysis columns. Store missing metrics as null rather than zero, and keep repeated observations separate if your project measures engagement changes.
Exclude protected-account content, direct messages and other nonpublic material. Authentication for a collection method does not expand this guide’s public-data scope. For broader planning, see practical considerations for social scraping.
Use the official X API: pricing and recent search
Direct answer: X’s current documentation names Pay-per-use and Enterprise access. Standard post reads cost $0.005 per returned resource (as of November 2026), according to the official X API pricing page, checked November 10, 2026.
Pay-per-use uses prepaid credits rather than a subscription. Its published cap is 3 million post reads per monthly billing cycle (as of November 2026); the same pricing page directs higher-volume requirements to Enterprise.
Search coverage: recent search covers the previous seven days and accepts page sizes from 10 to 100 (as of November 2026). The recent-search endpoint reference documents bearer authentication and continuation through meta.next_token.
Budget by returned resources, not request count. Additional resource types have separate prices, so inspect the billing impact of extra fields and expansions before scaling. Set a spending limit and compare actual charges with unique usable output.
X normally charges once per resource within a calendar day in UTC, even if you retrieve it repeatedly. This billing deduplication resets at midnight UTC and is a soft guarantee; use actual charges when comparing repeated runs.
Twitter scraper tools: practical alternatives
Compare authentication, coverage and billing units before choosing a Twitter scraper. The maintenance column below describes work your team should plan for; it is an engineering assessment, not a measured reliability ranking.
| Method | Authentication | Documented coverage | Billing unit | Maintenance to plan for |
|---|---|---|---|---|
| Official X API | Bearer token | Recent-search endpoint | Returned resources; see pricing above | Queries, pagination, schema and budget |
| Apify, API Dojo Tweet Scraper V2 | Apify API token for programmatic runs | Search and profile queries. Each query must return at least 50 tweets; queries expected to return fewer results require a different Actor. This Actor does not support single-post or conversation scraping and prohibits repeating the same query at short intervals. | From $0.40 per 1,000 tweets (as of November 2026) | Actor inputs, output mapping and run monitoring |
| TwitterAPI.io | X-API-Key header | Advanced tweet search | $0.15 per 1,000 tweets; $0.00015 minimum per request (as of November 2026) | Endpoint integration and pagination |
| ScrapeCreators | x-api-key header | Public profiles, post details and Google-indexed post search | $47 for 25,000 credits; most endpoints use one credit per request (as of November 2026) | Endpoint selection, coverage validation and output mapping |
| Python libraries: Twikit or twscrape | X account login or authorized session cookies | Documented search interfaces | Budget infrastructure and maintenance separately | Account sessions, dependencies and interface changes |
Competitor data: taken from each provider’s official pricing and documentation pages linked in this article, collected on November 10, 2026.
Sources: X pricing; X recent search; API Dojo Actor pricing and coverage; Apify authentication; TwitterAPI.io pricing; TwitterAPI.io search documentation; ScrapeCreators pricing; ScrapeCreators X endpoints; Twikit repository; twscrape repository.
These billing units are not interchangeable: a request, a returned post and a credit need not represent the same amount of useful data. ScrapeCreators describes its post search as Google-indexed discovery, so evaluate it against that scope rather than assuming equivalence to X recent search.
For a broader selection process, see choosing a social media collection tool.
How do you scrape twitter (X) step by step?
Define the query and output schema, authenticate, fetch a bounded sample, then validate and export it. Add pagination only after the first response contains the records you expect.
Step 1: Choose a public query and a collection cap. Record the query and collection time so later runs can be interpreted.
Step 2: Obtain an authorized X API bearer token and store it securely in the X_BEARER_TOKEN environment variable. Keep credentials out of source code and logs.
Step 3: Run this Python 3 example. It uses the Python standard HTTP library, so no additional package installation is needed. It requests two pages at most, deduplicates within the run and emits JSONL to standard output.
import json
import os
from urllib.parse import urlencode
from urllib.request import Request, urlopen
params = {
"query": "from:NASA",
"max_results": 10,
"post.fields": "created_at,public_metrics",
}
seen = set()
for _ in range(2):
url = "https://api.x.com/2/tweets/search/recent?" + urlencode(params)
request = Request(url, headers={
"Authorization": "Bearer " + os.environ["X_BEARER_TOKEN"]
})
with urlopen(request, timeout=30) as response:
page = json.load(response)
if page.get("errors"):
raise RuntimeError(page["errors"])
for post in page.get("data", []):
if post["id"] not in seen:
seen.add(post["id"])
print(json.dumps(post, ensure_ascii=False))
token = page.get("meta", {}).get("next_token")
if not token:
break
params["next_token"] = token
This example exports the returned post objects, not the complete schema described above. Before using it in a collection pipeline, add author information, a UTC collection timestamp, the query and the collection method.
Step 4: Save the API example as collect_x.py and run python collect_x.py > posts.jsonl. Check the process exit status before using the export: a failed run can leave a partial file. The page cap is a deliberate example safeguard, not an exhaustive collection setting. The code stops on request errors rather than retrying indefinitely.
Step 5: Validate required fields, deduplicate across runs using persistent IDs and flatten selected columns for CSV. Preserve the original JSONL so later cleanup changes do not require recollection.
Python example: collect tweets without an official API key
Direct answer: Twikit documents tweet searches without an official X API key, using account login and reusable cookies. No API key does not mean anonymous access; see the official Twikit repository.
Example installation, pinned to the release listed on the maintainer’s package page:
python -m pip install twikit==2.3.3
This example uses the documented Client, search_tweet and Result.next interfaces. Set X_USERNAME, X_EMAIL and X_PASSWORD securely, or use X_COOKIES_JSON for previously saved cookies from your authorized session. X_COOKIES_JSON must contain a JSON object mapping cookie names to string values, in the format returned by client.get_cookies(); do not pass a browser cookie-export array directly. Keep cookies secret.
import asyncio
import json
import os
from twikit import Client
async def main():
client = Client("en-US")
cookies = os.getenv("X_COOKIES_JSON")
if cookies:
client.set_cookies(json.loads(cookies))
else:
await client.login(
auth_info_1=os.environ["X_USERNAME"],
auth_info_2=os.environ["X_EMAIL"],
password=os.environ["X_PASSWORD"],
)
page = await client.search_tweet("from:NASA", "Latest")
seen = set()
for index in range(2):
for tweet in page:
if tweet.id not in seen:
seen.add(tweet.id)
print(json.dumps({"id": tweet.id, "text": tweet.text},
ensure_ascii=False))
if index == 1 or not page.next_cursor:
break
page = await page.next()
asyncio.run(main())
Capture output as JSONL. The example intentionally exports only identity and text; extend the schema after inspecting actual responses. X markup and internal interfaces can change, so successful installation does not prove live compatibility.
The twscrape README also documents search with authorized account cookies. That is evidence of a documented workflow, not a live success claim. The maintainer’s snscrape issue #996 records Twitter access failures; neither that historical report nor package availability establishes current working coverage. Validate any library before adopting it.
Troubleshooting authentication, pagination and browser rendering
Diagnose failures by layer: credentials, request parameters, pagination, returned schema and rendering. Changing proxies before identifying the failure can obscure the cause.
- Authentication: inspect the response body and credential configuration. Stop and resolve expired sessions or account challenges through the normal authorized flow.
- Pagination: preserve the query while advancing its continuation token. Stop on a missing token, a repeated token or your collection cap.
- Empty output: distinguish a valid empty result from an error payload, login page or parsing failure.
- Rate limiting: respect the documented reset or retry guidance. Use bounded retries and record failures.
- Schema changes: retain diagnostic responses with secrets removed, then compare the fields with your parser’s assumptions.
Do you need a headless browser? Consider one only when your authorized workflow requires rendered page content. A browser does not repair invalid credentials or establish complete coverage, and HTML parsing still requires selectors validated against current markup.
Proxy types, rotating requests and sticky sessions
Use a proxy when your workflow needs a specific network route or country, and test whether a stable session is necessary. A proxy cannot replace authentication, expand API permissions or guarantee access.
Product facts: DataImpulse is our proxy product.
Its residential proxies start at $1 per GB, with 90M+ IPs across 195+ countries, free country targeting and non-expiring traffic. Rotating and sticky sessions are available over HTTP, HTTPS and SOCKS5.
Prefer a sticky session when continuity matters across an authenticated sequence. Consider rotation between independent jobs only after checking the effect on sessions and results; rotating addresses does not remove a service’s limits.
Choose residential, mobile or datacenter routing from your measured requirements rather than an assumed detection ranking. Our proxy selection guide covers the broader decision.
Test your setup: completeness, failures and cost
Define success as unique, usable public records that meet your schema, not successful HTTP responses. Validate a small collection before increasing its scope.
Compare methods only where their documented coverage overlaps. Fix the target accounts and time interval, translate the query into each service’s supported syntax, and record unsupported filters. Evaluate Google-indexed discovery separately from X recent search. Cap each sample at 100 posts and respect each service’s minimum-result and repeat-query restrictions. This is a proposed test plan, not a report of completed measurements.
- Record execution dates, Python and package versions, query parameters and authentication method without secrets.
- Count unique IDs, duplicates, missing required fields, empty pages and failures.
- Record elapsed time, transferred GB, actual API charges and proxy charges separately.
- Check date boundaries and known public examples; record observable omissions without claiming exhaustive coverage.
- Calculate total collection cost divided by unique usable records.
Publish anonymized results with the method and sample size, and label them a snapshot rather than a benchmark. No X-specific success rate or comparative speed claim is established here.
Frequently Asked Questions
Frequently Asked Questions
Can I scrape Twitter without an official API key?
A method without an official API key can still require an authenticated account. Evaluate credentials, permitted access and maintenance requirements separately, and keep collection restricted to public records.
Is it legal to scrape Twitter (X)?
Public visibility alone is not enough to decide whether a particular collection and reuse is permitted. Apply the Access framework: validate public-data scope, contractual permission and applicable law separately from session authentication. Review the site’s terms, the applicable rules and your intended handling of personal information before proceeding.
Why does my Twitter scraper return no posts?
First inspect whether the response is an empty result, an authentication failure or an unexpected payload. Then check the query, date range and pagination state before changing the parser or network route.
How much does it cost to scrape Twitter?
Calculate API or scraper charges, infrastructure, proxy traffic and maintenance separately. Compare methods using cost per unique usable record, since a billed request and a returned post are different units.
Which proxies are best for scraping Twitter?
There is no universal choice established by this guide. Evaluate routing and session continuity in a small authorized workload, and measure useful output rather than assuming an IP type guarantees access.
Do I need a headless browser to collect tweets?
Choose rendering only when the collection workflow requires it. First establish whether a structured interface already supplies the public fields you need, then assess any remaining browser dependency.
How do I avoid duplicate tweets in an export?
Use the post ID as the deduplication key and persist processed IDs across runs. If repeated observations are intentional, retain the collection timestamp so engagement changes remain distinguishable.
Evaluate proxy routing with a bounded collection
If your public-data workflow needs country targeting or sticky sessions, consider DataImpulse residential proxies from $1 per GB. New customers can start with the one-time $5 Intro plan; subsequent top-ups start at $50. Confirm authentication, usable records and actual traffic costs before expanding collection.
Last updated: November 10, 2026.
