Twitter (X) and Scrapy: Why Plain Spiders Get Nothing and What Works in 2026

- Plain spider, 0 items: x.com's
robots.txtsaysDisallow: /forUser-agent: *; with Scrapy's project defaultROBOTSTXT_OBEY = True, our run loggedrobotstxt/forbidden: 2and wrote an empty file. - One logged-out load is a JavaScript shell: 172,803 bytes, 21 inline
<script>tags, 5 posts (one pinned) and a sign-up prompt. There is no next page for a spider to follow. - scrapy-playwright (BSD-3-Clause,
scrapy-plugins/scrapy-playwright) is a download handler that fetches pages through Playwright; it renders JavaScript, nothing more. It does not change what x.com allows. - API-backed spider:
start_requestshits/twitter/user/last_tweets,parsefollowshas_next_page/next_cursor, a pipeline drops repeats byid. Our crawl: 50 requests, 980 posts, 40 duplicates dropped, 940 unique. - Cost: 14,700 credits = $0.147 at $0.15 per 1,000 posts returned; the same 980 reads at the official X API rate card ($0.005 per post read) are $4.90, about 33x.
- Throughput and payload: 3.5 s per 20-post page and 322 posts a minute through a shared 5 req/s limiter; 7.5 KB of JSON per post; text, timestamps and all six counters present on 100% of posts.
Scrapy is the framework many Python developers reach for when they need to crawl something at scale: a scheduler, a throttle, retries, item pipelines and feed exports, all in one process. So when the target is X (Twitter), the first instinct is a spider with start_urls = ["https://x.com/..."] and a few CSS selectors. That spider returns nothing, and the reasons are worth understanding before you spend a day on selectors.
This guide runs both spiders. First the plain one, against two public organization profiles, with Scrapy's default settings, so you can see exactly where it stops. Then an API-backed spider that keeps everything Scrapy is good at but fetches JSON instead of HTML. We ran the second one on five organization timelines and timed every page, counted every field and priced the crawl, so the numbers below are measured, not estimated.
Scope: this page is about Scrapy. For a browser-driver walkthrough see the Selenium guide, for a broader overview of collection methods see the scraping guide, and for a tool-by-tool roundup see the scraper comparison, all linked at the end.
980 posts for $0.147
What a plain Scrapy spider gets from x.com
We created the smallest possible spider: two start URLs (x.com/github and x.com/vercel, both organization accounts), a parse that only records status and size, DOWNLOAD_DELAY = 10, one request at a time, and ROBOTSTXT_OBEY = True, which is the value scrapy startproject writes into every new project's settings.py (per the Scrapy settings reference).
Result. Scrapy sent exactly one request, to https://x.com/robots.txt, which answered 200. Both profile requests were then dropped inside Scrapy before they reached the network: the stats show robotstxt/forbidden: 2, downloader/exception_type_count/scrapy.exceptions.IgnoreRequest: 2, and no item_scraped_count. The output file was an empty JSON array.
Why. x.com's robots.txt has named groups for search crawlers (Googlebot and Bingbot get specific Allow and Disallow lines), full blocks for several AI and social crawlers (Google-Extended, Applebot-Extended, FacebookBot, Discordbot and Meta's crawlers), and a catch-all group: User-agent: * with Disallow: /. A Scrapy spider is not one of the named crawlers, so it falls under the catch-all and every path on the site is off-limits to it.
What that means for you. Turning ROBOTSTXT_OBEY off does not make the target any more willing; it only removes the check that told you the site does not want generic crawlers. The rest of this page assumes you keep it on for websites, and use an API for X data.
import scrapy
class PlainXSpider(scrapy.Spider):
"""What a plain spider gets from x.com. Do not use this to collect posts."""
name = "plain_x"
custom_settings = {
"ROBOTSTXT_OBEY": True, # the default in every `scrapy startproject` settings.py
"DOWNLOAD_DELAY": 10,
"CONCURRENT_REQUESTS": 1,
}
start_urls = ["https://x.com/github", "https://x.com/vercel"]
def parse(self, response):
yield {"url": response.url, "status": response.status, "bytes": len(response.body)}
# scrapy runspider plain_spider.py -O out.json
# Log: robotstxt/request_count 1, robotstxt/forbidden 2, item_scraped_count absent -> out.json is []What one logged-out page load contains
To show what the HTML looks like without crawling, we loaded x.com/github once with curl, logged out, the way a browser's first request would. The response was HTTP 200, 172,803 bytes of text/html, and the page title read GitHub (@github) / X.
What is inside. 21 inline <script> tags carry the app and its state; the visible markup is a profile header (name, bio, location, joined date, following and follower counts) followed by 5 post cards (one of them pinned) and then a log-in or sign-up panel. The post objects sit in a serialized state blob next to the markup, not in a documented format.
What is missing. There is no pagination link, no cursor a spider could follow, and nothing past those first cards. Replies, search results, follower lists and older posts all need a logged-in session in the web app, which is exactly where X's automation rules apply to the account doing the browsing.
The markup and the embedded state blob are internal to X's web app and change when X ships a new build. A selector that matches today has no contract behind it, which is the core maintenance cost of any HTML-based approach.
What scrapy-playwright changes, and what it does not
scrapy-playwright is an official Scrapy plugin (GitHub scrapy-plugins/scrapy-playwright, BSD-3-Clause). Its README describes it as a Scrapy download handler that performs requests using Playwright for Python. On PyPI the current release is 0.0.48 and it requires Python 3.10 or newer.
How it plugs in. Per its setup docs you install it with pip install scrapy-playwright and playwright install firefox chromium, point DOWNLOAD_HANDLERS for https at scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler, set TWISTED_REACTOR to twisted.internet.asyncioreactor.AsyncioSelectorReactor, and mark the requests that need a browser with the playwright key in Request.meta. Requests without that key still go through Scrapy's normal downloader.
What it changes. Pages are rendered by a real browser engine, so content that a JavaScript app builds after load becomes visible to your parse callback. That is useful on sites whose data is public and whose robots.txt allows you in.
What it does not change. On x.com it does nothing about the Disallow: / rule (Scrapy's robots check runs before any download handler), nothing about the log-in prompt after the first cards, and nothing about X's automation rules once a session is involved. It also makes each page far heavier: a browser context, images, scripts and a long-running process per crawl. We describe it here so you know what it is; we do not show a browser-based spider for x.com.
The clean option: a Scrapy spider that calls a JSON API
Scrapy does not care whether a response is HTML or JSON. scrapy.Request can carry any header, response.json() parses the body, and everything else (scheduler, retries, throttle, pipelines, feed exports) works unchanged. So the fix is not a smarter selector; it is a different target.
start_requests. One request per account to /twitter/user/last_tweets with userName and an empty cursor, plus the X-API-Key header. No browser, no x.com pages and no X account are needed for reads.
parse. Read data.tweets[] (up to 20 posts per page, newest first), yield one item per post, then check the top-level has_next_page and next_cursor. If there is another page and you are under your page cap, yield the next request with that cursor. An error response comes back as status: "error" with the reason in msg, so log it and stop that account.
Item pipeline. Keep a set of seen id values and drop repeats before writing JSONL. This is not theoretical: in our crawl one of the five accounts returned 40 posts twice across its pages, and the pipeline removed all 40.
What you get back. Each item is a typed JSON object: text, createdAt, lang, six counters (likeCount, retweetCount, replyCount, quoteCount, viewCount, bookmarkCount), entities, extendedEntities.media[], quoted_tweet, retweeted_tweet and a nested author with 33 keys. No HTML parsing, no selectors to maintain.
The complete spider is in the code block at the end of this page. We checked it locally with Scrapy 2.13: it loads, the pipeline registers, and when we fed the five saved API pages through parse and the pipeline offline, it produced the same unique count as the study. The live crawl itself went through our Python study client, not through this Scrapy file, because the run's API key is not readable by the build script.
Keyword crawls. The same pattern works for searches: point the request at /twitter/tweet/advanced_search with query and queryType, and read tweets[], has_next_page and next_cursor from the top level of the response instead of from under data. The short spider below shows only what changes.
from urllib.parse import urlencode
import scrapy
BASE = "https://api.twitterapi.io"
class XSearchSpider(scrapy.Spider):
"""Keyword crawl: same pattern, search endpoint, top-level tweets[]."""
name = "x_search"
custom_settings = {"ROBOTSTXT_OBEY": False, "DOWNLOAD_DELAY": 5, "CONCURRENT_REQUESTS_PER_DOMAIN": 1}
def __init__(self, q="scrapy lang:en", max_pages="5", **kw):
super().__init__(**kw)
self.q, self.max_pages = q, int(max_pages)
def start_requests(self):
yield self.page("", 1)
def page(self, cursor, n):
params = {"query": self.q, "queryType": "Latest", "cursor": cursor}
return scrapy.Request(f"{BASE}/twitter/tweet/advanced_search?" + urlencode(params),
headers={"X-API-Key": self.settings.get("TWITTERAPI_IO_KEY")},
callback=self.parse, cb_kwargs={"n": n}, dont_filter=True)
def parse(self, response, n):
body = response.json()
for t in body.get("tweets") or []:
yield {"id": t["id"], "created_at": t.get("createdAt"), "text": t.get("text"),
"likes": t.get("likeCount"), "views": t.get("viewCount")}
if body.get("has_next_page") and body.get("next_cursor") and n < self.max_pages:
yield self.page(body["next_cursor"], n + 1)
# scrapy runspider search_spider.py -s TWITTERAPI_IO_KEY=... -a q="scrapy lang:en" -O search.jsonlSettings: match DOWNLOAD_DELAY and AutoThrottle to the rate limit
Scrapy's throttle settings map directly onto an API's rate limit. The account limits on twitterapi.io are 0.2 requests per second before the first payment, 20 once paid, 50 on the Scale plan and 500 on Business (up to 1,000 on request).
DOWNLOAD_DELAY. The minimum gap between two requests to the same domain. At 0.2 requests per second set it to 5 seconds. Once paid, 0.1 seconds with a few concurrent requests stays well inside 20 per second.
CONCURRENT_REQUESTS_PER_DOMAIN. All requests go to one host, so this caps parallelism. Keep it at 1 on the free rate and raise it only after you raise the limit.
AutoThrottle. Per the Scrapy docs it is off by default, starts at a 5-second delay, aims for 1.0 concurrent request per remote site and never goes below DOWNLOAD_DELAY; non-200 responses cannot shorten the delay. That makes it a safe companion: it slows down when the API slows down.
Retries. Add 429 to RETRY_HTTP_CODES so a burst over the limit is retried after the delay instead of being lost.
robots.txt. The API host answers a robots.txt request with 401 when no key is sent, because the host is a JSON API and not a website. Set ROBOTSTXT_OBEY = False on the API spider only; keep it on for any spider that crawls web pages.
# settings.py for an API-backed project (or custom_settings on the spider)
ROBOTSTXT_OBEY = False # the API host is JSON only; its robots.txt answers 401 without a key
CONCURRENT_REQUESTS_PER_DOMAIN = 1
# Before your first payment the account allows 0.2 requests/s: one request every 5 s.
DOWNLOAD_DELAY = 5
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 5
AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Once paid (20 requests/s), for example:
# DOWNLOAD_DELAY = 0.1
# CONCURRENT_REQUESTS_PER_DOMAIN = 4
RETRY_HTTP_CODES = [429, 500, 502, 503, 504]
RETRY_TIMES = 4
FEEDS = {"posts-%(time)s.jsonl": {"format": "jsonlines", "encoding": "utf8"}}The study: an API-backed crawl of five organization timelines
We pulled up to 10 pages from each of five organization accounts (github, vercel, Docker, ThePSF, nodejs) through /twitter/user/last_tweets, timing each account's crawl as one job. The crawl made 50 requests and returned 980 posts; after the id dedupe 940 were unique. The nodejs timeline ran out at 180 posts (has_next_page false on page 10), and Docker repeated 40 posts across pages.
Throughput. 3.5 seconds per page on average and 322 unique posts a minute. The client spaces requests through a 5 requests per second limiter that other jobs on the same machine were sharing at the time, so a single dedicated crawler at the same rate limit would be at least this fast.
Payload. 7.2 MB of raw JSON for 940 posts, about 7.5 KB per post, because every item carries its author object and any quoted or reposted post in full. Write only the fields you need in the pipeline if storage matters.
Cadence. The five accounts post between 0.29 and 2.59 times a day, so 10 pages reach back anywhere from about 77 days (github) to about 612 days (nodejs). A daily incremental crawl of one such account is usually a single page.

What each item carries: field presence across 940 posts
A spider is only as useful as the fields it can fill. We counted, for each field, the share of posts where it is present and not null or empty (a counter of 0 counts as present).
What this means for your item class. Declare the always-present fields as required and everything else as optional. inReplyToId is empty because last_tweets leaves replies out unless you pass includeReplies=true; it is not a missing feature. place was empty on every post in this sample, so do not build a location feature on organization timelines.
Reposts need a decision. 20.1% of the items are reposts; their text is the repost wrapper and the original lives in retweeted_tweet. Decide in parse whether to keep them, unwrap them or drop them, because a timeline crawl of an account that reposts a lot (nodejs: 44.4%) is largely other accounts' posts.

What the crawl cost, and the same crawl on the official X API
Timeline reads on twitterapi.io are billed per post returned: 15 credits per post, which is $0.15 per 1,000 posts ($1 = 100,000 credits). A full 20-post page costs $0.003. Our crawl returned 980 posts, so it used 14,700 credits, or $0.147. The 40 duplicates were billed too, because they were returned; dedupe saves storage, not credits.
Official X API. The pay-per-usage rate card on docs.x.com lists $0.005 per post read and $0.010 per user read, with pay-per-usage capped at 3 million post reads a month and Enterprise above that. At $5 versus $0.15 per 1,000 posts, the official route costs about 33x more for the same reads.
Empty pages. A request that returns nothing is billed at the 15-credit minimum ($0.00015), so an incremental spider that checks a quiet account and finds no new posts costs very little. New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); purchased credits never expire. See the pricing page for current amounts and the monthly plans.
How we collected this
Question. What does an API-backed Scrapy crawl of about 1,000 X posts cost in requests, time and money, what does each item carry, and what does a plain Scrapy spider get from x.com instead?
Accounts. Five public organization accounts: github, vercel, Docker, ThePSF and nodejs. Timelines via /twitter/user/last_tweets (default, replies excluded), up to 10 pages each, newest first. Plain-spider side: Scrapy 2.13 in a throwaway virtual environment, ROBOTSTXT_OBEY = True, two profile URLs, plus one logged-out curl load of x.com/github.
Sample and window. 50 API requests, 980 posts returned, 940 unique. Each account's window runs from its oldest to its newest sampled post at collection time. Collected in 2026.
What the sample cannot show. Five organization timelines are not representative of all accounts: personal accounts, replies, search results and media-heavy feeds will have different field presence and payload sizes. Wall time depends on the rate limiter and on other traffic sharing it. The plain-spider result reflects x.com's robots.txt and markup at collection time; both can change.
Privacy. Aggregates only, organization accounts only, no analysis of reposted or quoted authors. Raw pages stayed out of the published study folder because reposts and quotes carry other accounts; the folder holds the protocol, the analysis script, the results and de-identified per-post rows without ids, URLs, text or handles.
"""API-backed Scrapy spider: X (Twitter) timelines as JSON, no browser, no x.com pages.
Run: export TWITTERAPI_IO_KEY=... (from your twitterapi.io dashboard)
scrapy runspider x_timeline_spider.py -a accounts=github,vercel -a max_pages=10
Output: posts.jsonl (one post per line, deduplicated by id)
"""
import json
import os
from urllib.parse import urlencode
import scrapy
from scrapy.exceptions import DropItem
BASE = "https://api.twitterapi.io"
class DedupeJsonlPipeline:
"""Drop posts already seen (timelines can repeat a post across pages), write the rest as JSONL."""
def open_spider(self, spider):
self.seen = set()
self.fh = open("posts.jsonl", "a", encoding="utf-8")
def close_spider(self, spider):
self.fh.close()
def process_item(self, item, spider):
if item["id"] in self.seen:
raise DropItem(f"duplicate post {item['id']}")
self.seen.add(item["id"])
self.fh.write(json.dumps(item, ensure_ascii=False) + "\n")
return item
class XTimelineSpider(scrapy.Spider):
name = "x_timeline"
custom_settings = {
# api.twitterapi.io is a JSON API, not a website: it has no robots.txt (401 without a key).
"ROBOTSTXT_OBEY": False,
# Match the account's rate limit: 0.2 req/s before the first payment -> one request every 5 s.
# After paying (20 req/s) you can lower DOWNLOAD_DELAY to 0.1 and raise concurrency.
"CONCURRENT_REQUESTS_PER_DOMAIN": 1,
"DOWNLOAD_DELAY": 5,
"AUTOTHROTTLE_ENABLED": True,
"AUTOTHROTTLE_START_DELAY": 5,
"AUTOTHROTTLE_TARGET_CONCURRENCY": 1.0,
"RETRY_HTTP_CODES": [429, 500, 502, 503, 504],
"RETRY_TIMES": 4,
"ITEM_PIPELINES": {DedupeJsonlPipeline: 300},
}
def __init__(self, accounts="github", max_pages="10", **kw):
super().__init__(**kw)
self.accounts = [a.strip() for a in accounts.split(",") if a.strip()]
self.max_pages = int(max_pages)
self.key = os.environ.get("TWITTERAPI_IO_KEY", "")
def api_request(self, user, cursor, page):
url = f"{BASE}/twitter/user/last_tweets?" + urlencode({"userName": user, "cursor": cursor})
return scrapy.Request(url, headers={"X-API-Key": self.key}, callback=self.parse,
cb_kwargs={"user": user, "page": page}, dont_filter=True)
async def start(self): # Scrapy 2.13+; older versions call start_requests()
for r in self.start_requests():
yield r
def start_requests(self):
if not self.key:
self.logger.error("set TWITTERAPI_IO_KEY first")
return
for user in self.accounts:
yield self.api_request(user, "", 1)
def parse(self, response, user, page):
body = response.json()
if body.get("status") == "error":
self.logger.warning("%s: %s", user, body.get("msg"))
return
for t in (body.get("data") or {}).get("tweets") or []:
author = t.get("author") or {}
media = (t.get("extendedEntities") or {}).get("media") or []
yield {
"id": t["id"],
"url": t.get("url"),
"created_at": t.get("createdAt"),
"text": t.get("text"),
"lang": t.get("lang"),
"likes": t.get("likeCount"),
"reposts": t.get("retweetCount"),
"replies": t.get("replyCount"),
"quotes": t.get("quoteCount"),
"views": t.get("viewCount"),
"is_repost": bool(t.get("retweeted_tweet")),
"is_quote": bool(t.get("quoted_tweet")),
"media_types": [m.get("type") for m in media],
"author": author.get("userName"),
"source_account": user,
}
if body.get("has_next_page") and body.get("next_cursor") and page < self.max_pages:
yield self.api_request(user, body["next_cursor"], page + 1)
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
Can Scrapy scrape Twitter (X)?
Not from x.com pages in any useful way. x.com's robots.txt disallows every path for crawlers without a named rule, and Scrapy obeys robots.txt by default in new projects, so a plain spider gets 0 items. A logged-out page load shows a handful of posts and a log-in prompt with no next page. Scrapy works well when its requests go to a JSON API instead: same spider structure, X-API-Key header, cursor pagination in parse.
Why does my Scrapy spider return an empty result on x.com?
Check the stats at the end of the log. If you see robotstxt/forbidden, robots.txt filtered the requests before they were sent. If you disabled that check, the HTML you get is a JavaScript app shell: the content is built by scripts and the first few cards are followed by a log-in panel, so CSS selectors written against the page you see in a logged-in browser match nothing.
Does scrapy-playwright make Twitter scraping work?
It renders JavaScript by sending marked requests through Playwright, which solves the empty-shell problem on sites that allow crawling. It does not change x.com's robots.txt, the log-in prompt or X's automation rules, and it is much heavier per page. For X data a JSON API removes the need for a browser entirely.
How do I paginate X results in Scrapy?
Read the top-level has_next_page and next_cursor from each JSON response in parse. If has_next_page is true, yield a new scrapy.Request with cursor=<next_cursor> and the same header, and stop at a page cap you choose. Use dont_filter=True so Scrapy's duplicate filter does not drop requests that differ only by cursor, and dedupe items by id in a pipeline.
What DOWNLOAD_DELAY should I use with an API?
Derive it from the rate limit. At 0.2 requests per second (twitterapi.io before the first payment) use DOWNLOAD_DELAY = 5 with one concurrent request; after paying (20 requests per second) 0.1 seconds with a few concurrent requests stays inside the limit. Turn on AutoThrottle and add 429 to RETRY_HTTP_CODES.
How much does it cost to crawl 1,000 tweets with Scrapy and an API?
On twitterapi.io, $0.15 per 1,000 posts returned (15 credits per post). Our crawl of 980 posts cost $0.147. The same reads at the official X API's pay-per-usage rate of $0.005 per post read would be $4.90.
Do I need an X account or login to use the API-backed spider?
No. Reads need only an API key in the X-API-Key header; no X account and no log-in. Keep the key in an environment variable or a Scrapy setting passed on the command line, never in the spider file you commit.
Can I crawl keyword searches instead of timelines?
Yes. Swap the endpoint for /twitter/tweet/advanced_search with query and queryType (Latest or Top). The response puts tweets[], has_next_page and next_cursor at the top level instead of under data, so adjust the field path in parse.
Continue
- Scrapy docs: settings reference (ROBOTSTXT_OBEY in startproject, DOWNLOAD_DELAY, CONCURRENT_REQUESTS_PER_DOMAIN)
- Scrapy docs: AutoThrottle extension (defaults, DOWNLOAD_DELAY as lower bound)
- scrapy-playwright on GitHub (Playwright download handler for Scrapy, BSD-3-Clause)
- Scrapy on PyPI (current release and Python requirement)
- twitterapi.io API reference: user last tweets (20 per page, has_next_page, next_cursor)
- X API pay-per-usage pricing ($0.005 per post read, 3M monthly cap)
- X (Twitter) API hub: endpoints, auth and pricing
- Twitter scraping guide: every collection method compared
- Cursor pagination with has_next_page and next_cursor
- Twitter scraper tools compared
- Selenium and X: what a browser driver runs into
- Web scraping vs an API for social data
- Twitter API rate limits explained
- Pay-per-use pricing: $0.15 per 1,000 posts
- twitterapi.io API reference
- 01Community Notes on X (Twitter): Violations, Ratings and the Public Data
- 02How to Cite a Tweet (a Post on Twitter / X) in MLA, APA and Chicago
- 03Twitter (X) Airtable Integration: Save Tweets to a Base With a Script
- 04How to advertise on Twitter (X): a step-by-step guide to X Ads, with real brand format data
- 05Tay Bot on Twitter (X): What Happened to Microsoft's Chatbot, and What AI Agents Should Learn
- 06Twitter (X) Follow API: Follow, Verify and Undo a Follow from Code
- 07Twitter (X) Shopify Integration: Post Products and Pull Mentions Back
- 08Twitter (X) Enterprise API: What It Includes, Who Needs It, and What It Costs
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.