Category:Scraping Use CasesView as Markdown
Twitter (X) Scraping in 2026: Scrape Posts and Profiles Without Login

Web Scraping Expert
Twitter scraping means collecting public data from X (formerly Twitter), such as tweets, profile details and engagement counts, with a script instead of copying it by hand.
X changed how it serves pages to logged-out visitors. Profile and post pages now arrive as finished HTML, so you no longer need a headless browser, scrolling or data-testid selectors to scrape tweets from them. One plain request returns a profile's name, bio, counts and its latest few posts with their metrics.
The catch is that this is most of what X shows without a login. Search, hashtags, followers, trends and older posts all send you to the login page.
This guide gives you three Python scrapers for the public part (tweets from a profile, profile details, and a single post with its replies), all tested against x.com. It also maps what sits behind the login wall and what to use instead.
Can You Scrape Twitter Without Logging In?
We requested each page type through the Scrape.do API and checked where it landed:
| Page | Example URL | Logged-out result |
|---|---|---|
| Profile | x.com/NatGeo |
Public: name, bio, location, website, join date, counts, avatar, banner and the latest few posts |
| Single post | x.com/NatGeo/status/2124548463689974189 |
Public: the post, its metrics and a few replies |
| oEmbed | publish.x.com/oembed?url=... |
Public JSON: author, post text and embed HTML, no key needed |
| Replies and Media tabs | x.com/NatGeo/with_replies, x.com/NatGeo/media |
Redirect to the login page |
| Search, including Latest | x.com/search?q=...&f=live |
Redirect to the login page |
| Hashtag | x.com/hashtag/WolvesUpClose |
Redirect to the login page |
| Followers | x.com/NatGeo/verified_followers |
Redirect to the login page |
| Trending | x.com/explore/tabs/trending |
Redirect to the login page |

Scraping public pages that anyone can see without logging in is legal. US courts ruled for scrapers of public data in hiQ v. LinkedIn, Meta v. Bright Data and X Corp. v. Bright Data, summarized in the FAQ.
The scrapers below use no login and no account automation, which keeps them on the public side. Profile data is still personal data under the EU's GDPR and similar laws, so store and use it carefully. Our guide to the ethics of web scraping covers good practice.
What Changed on X for Scrapers?
If you followed an X scraping tutorial written before X rebuilt its logged-out pages, including the earlier version of this one, this is why it stopped working:
| What older guides told you | What x.com does now |
|---|---|
| Render JavaScript, or you get "JavaScript is not available" | The HTML already holds the profile and the posts, and a plain request returns them |
Wait for article[data-testid="tweet"] |
The page has no data-testid attributes at all. That selector matches nothing, even after rendering |
| Scroll to load more tweets | Each profile shows its latest few posts to logged-out visitors. Scrolling in a rendered browser added none, and the network log showed no request for more posts |
| Scrape trends from the "What's happening" sidebar | Logged-out pages have no trends sidebar, and the trending page redirects to login |
This also changes the cost. A plain Scrape.do request costs fewer credits than one with render=true (request costs). Rendering adds nothing on X, so skip it.
Is the X API Worth It for Scraping?
The X API charges per item: you pay per post read and per user read, with monthly caps. See X's API pricing page for current rates.
Scraping a public profile page gets you the profile details and the latest posts in one request. That suits profile snapshots, follower counts over time and engagement tracking on recent posts.
The API is the right tool for what the logged-out web hides: search, full timelines and follower lists.
Do You Need a Scraping API to Scrape X?
We sent the same profile requests straight from one machine, a second apart, and they all came back with posts. For a handful of pages you may not need anything else.
Volume is where it changes. X does rate-limit: its own syndication endpoint answered one of our direct requests with 429 Rate limit exceeded. The Scrape.do Web Scraping API handles proxies, retries and concurrency for you, and you pay only for successful requests. Keep your request rate modest either way.
What Do You Need to Scrape Twitter with Python?
You need:
- Python 3 with Requests and Beautiful Soup:
pip install requests beautifulsoup4 - A Scrape.do account. It comes with free credits to start (pricing)
- Your API token from the dashboard, set as an environment variable:
export SCRAPE_DO_TOKEN="<your_token>"
On Windows PowerShell, use $env:SCRAPE_DO_TOKEN = "<your_token>". Every script below reads the token from that variable.
Every request goes to one endpoint, with the X page as the url parameter. Requests URL-encodes it for you:
response = requests.get(
"https://api.scrape.do/",
params={"token": SCRAPE_DO_TOKEN, "url": "https://x.com/NatGeo"},
timeout=60,
)
There is no render and no waitSelector. That plain call returned every X page we scraped for this tutorial.
How Do You Scrape Tweets from a Profile?
Where Is Each Tweet Field in the HTML?
Each post on a profile page is an <article>. Its class names are generated utility classes such as flex flex-col gap-1, which can change with any X release, so skip them. These hooks found the URL, author, handle, text and metrics of every post on every profile we tested:
| Field | Where it is | Selector |
|---|---|---|
| Post URL and ID | The link to /status/<id> |
a[href*="/status/"], the one ending in digits |
| Author name | The text of the profile link | a[href^="/"] div[dir="auto"] |
| Handle | The span that starts with @ |
a span |
| Text | The block with a lang attribute |
div[lang] |
| Images | Media served from pbs.twimg.com/media/ |
img[src*="pbs.twimg.com/media/"] |
| Video | The poster frame | video[poster] |
| Links | t.co short links | a[href^="https://t.co/"] |
| Metrics | The label on the engagement bar | div[role="group"][aria-label] |
Three details matter:
- Metrics come as one label, in the form
<n> replies, <n> reposts, <n> likes, <n> bookmarks, <n> views. X leaves zero counts out, so a reply with no reposts or bookmarks reads<n> replies, <n> likes, <n> views. Parse each number by its name, never by its position. - The date is not in the text. The page shows "16h" or "Nov 18" and fills it in with a script. You can get the exact time from the post ID instead: it is a Snowflake ID, and shifting it right by 22 bits gives milliseconds since X's epoch. On the posts we checked, this matched the timestamp in the page to within a second.
- A quoted post is an
<article>inside another<article>. Skip nested ones, or a quote shows up as a separate post.
What Does the Full Tweet Scraper Look Like?
This script fetches one profile, parses every post on it and saves them to posts.csv:
# pip install requests beautifulsoup4
import csv
import os
import re
from datetime import datetime, timezone
import requests
from bs4 import BeautifulSoup
# Set SCRAPE_DO_TOKEN in your environment, or paste your token over <your_token>
SCRAPE_DO_TOKEN = os.environ.get("SCRAPE_DO_TOKEN", "<your_token>")
PROFILE_URL = "https://x.com/NatGeo"
# Labels X writes into the engagement bar, singular and plural
METRIC_KEYS = {
"reply": "replies", "replies": "replies",
"repost": "reposts", "reposts": "reposts",
"like": "likes", "likes": "likes",
"bookmark": "bookmarks", "bookmarks": "bookmarks",
"view": "views", "views": "views",
}
METRIC_RE = re.compile(r"([\d,]+) (" + "|".join(METRIC_KEYS) + r")\b")
def fetch(url):
# A plain request (1 credit): X serves logged-out pages as server-rendered HTML
response = requests.get(
"https://api.scrape.do/",
params={"token": SCRAPE_DO_TOKEN, "url": url},
timeout=60,
)
response.raise_for_status()
return BeautifulSoup(response.text, "html.parser")
def parse_metrics(label):
# "2 replies, 15 likes, 2360 views": zero counts are left out, so match by name
metrics = dict.fromkeys(["replies", "reposts", "likes", "bookmarks", "views"], 0)
for value, name in METRIC_RE.findall(label or ""):
metrics[METRIC_KEYS[name]] = int(value.replace(",", ""))
return metrics
def created_at(post_id):
# Post IDs are Snowflake IDs: the top bits are milliseconds since 2010-11-04
ms = (int(post_id) >> 22) + 1288834974657
return datetime.fromtimestamp(ms / 1000, timezone.utc).isoformat()
def parse_post(article):
status_link = next(
(a for a in article.select('a[href*="/status/"]') if re.search(r"/status/\d+$", a["href"])),
None,
)
if status_link is None:
return None
path = status_link["href"]
post_id = path.rsplit("/", 1)[-1]
handle = next((s.get_text(strip=True) for s in article.select("a span") if s.get_text(strip=True).startswith("@")), None)
name_element = article.select_one('a[href^="/"] div[dir="auto"]')
text_element = article.select_one("div[lang]")
metrics_element = article.select_one('div[role="group"][aria-label]')
return {
"url": "https://x.com" + path,
"id": post_id,
"created_at": created_at(post_id),
"author": name_element.get_text(strip=True) if name_element else None,
"handle": handle,
"pinned": "Pinned" in article.get_text(" ", strip=True)[:40],
"text": text_element.get_text(" ", strip=True) if text_element else None,
"images": [img["src"] for img in article.select('img[src*="pbs.twimg.com/media/"]')],
"videos": [video["poster"] for video in article.select("video[poster]")],
"links": sorted({a["href"] for a in article.select('a[href^="https://t.co/"]')}),
**parse_metrics(metrics_element["aria-label"] if metrics_element else ""),
}
soup = fetch(PROFILE_URL)
posts = []
for article in soup.select("article"):
# A quoted post is an <article> inside another one: keep top-level posts only
if article.find_parent("article"):
continue
post = parse_post(article)
if post:
posts.append(post)
if not posts:
raise SystemExit("No posts found: the page hit the login wall or X changed its markup")
with open("posts.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(posts[0].keys()))
writer.writeheader()
writer.writerows(posts)
print(f"Saved {len(posts)} posts to posts.csv")
for post in posts:
print(post["created_at"][:16], post["likes"], "likes |", (post["text"] or "")[:60])
Run it, and you get the latest posts, the pinned one first. Sample output:
Saved 5 posts to posts.csv
2026-11-18T20:00 226 likes | The wolf pack is on the prowl, and we have a pack of our own
2026-11-22T17:00 225 likes | In this image from our Pictures of the Year 2026, Nat Geo ph
2026-11-22T14:00 468 likes | Presented by National Geographic Society in partnership with
2026-11-21T22:00 311 likes | Presented by National Geographic Society in partnership with
2026-11-21T17:00 458 likes | In this image from our Pictures of the Year 2026, Nat Geo ph
Each row of posts.csv holds the URL, ID, timestamp, author, handle, pinned flag, text, image and video URLs, t.co links and the five metrics.
How Do You Scrape X Profile Information?
The profile header sits on the same page, so the same 1-credit request covers it. Here is where each field lives:
| Field | Selector or source |
|---|---|
| Name | h1 |
| Verified badge | [aria-label="Verified account"] next to the h1 |
| Bio | The og:description meta tag |
| Location | The row holding svg[data-icon="icon-location-pin"] |
| Website | The row holding svg[data-icon="icon-link"]: a t.co link whose text is the domain |
| Join date | a[href$="/about"] |
| Following and followers | The first span in a[href$="/following"] and a[href$="/verified_followers"] |
| Post count | The "73.7K posts" text under the name |
| Avatar and banner | a[href$="/photo"] img and a[href$="/header_photo"] img |
The icon names (icon-location-pin, icon-link) describe what the row holds, which makes them steadier hooks than the generated classes around them.
X shows rounded counts such as "28M" and "73.7K", so the script converts them to numbers. Treat them as approximate.
On the profiles we tested, the parser filled every field the page shows. A field comes back empty only when the account leaves it blank, such as a profile with no location.
# pip install requests beautifulsoup4
import json
import os
import re
import requests
from bs4 import BeautifulSoup
SCRAPE_DO_TOKEN = os.environ.get("SCRAPE_DO_TOKEN", "<your_token>")
PROFILE_URL = "https://x.com/NatGeo"
def fetch(url):
response = requests.get(
"https://api.scrape.do/",
params={"token": SCRAPE_DO_TOKEN, "url": url},
timeout=60,
)
response.raise_for_status()
return BeautifulSoup(response.text, "html.parser")
def to_int(count):
# "28M" -> 28000000, "73.7K" -> 73700, "178" -> 178
if not count:
return None
count = count.replace(",", "").strip()
scale = {"K": 1_000, "M": 1_000_000, "B": 1_000_000_000}.get(count[-1].upper(), 1)
number = count[:-1] if scale > 1 else count
return int(float(number) * scale)
def meta(soup, prop):
tag = soup.select_one(f'meta[property="{prop}"]')
return tag["content"] if tag else None
def icon_row(soup, icon):
# Location, website and join date each sit next to an icon with a stable data-icon name
svg = soup.select_one(f'svg[data-icon="{icon}"]')
return svg.parent if svg else None
def count_before(soup, href_suffix):
link = soup.select_one(f'a[href$="{href_suffix}"]')
first_span = link.select_one("span") if link else None
return first_span.get_text(strip=True) if first_span else None
soup = fetch(PROFILE_URL)
name_element = soup.select_one("h1")
handle_match = re.search(r"\(@(\w+)\)", meta(soup, "og:title") or "")
location_row = icon_row(soup, "icon-location-pin")
website_row = icon_row(soup, "icon-link")
website_link = website_row.select_one("a") if website_row else None
joined_element = soup.select_one('a[href$="/about"]')
posts_match = re.search(r"([\d.,]+[KMB]?) posts", soup.get_text(" ", strip=True))
avatar = soup.select_one('a[href$="/photo"] img')
banner = soup.select_one('a[href$="/header_photo"] img')
profile = {
"name": name_element.get_text(strip=True) if name_element else None,
"handle": handle_match.group(1) if handle_match else None,
"verified": bool(name_element and name_element.parent.select_one('[aria-label="Verified account"]')),
"bio": meta(soup, "og:description"),
"location": location_row.get_text(strip=True) if location_row else None,
"website": website_link.get_text(strip=True) if website_link else None,
"website_tco": website_link["href"] if website_link else None,
"joined": joined_element.get_text(strip=True).replace("Joined ", "") if joined_element else None,
"following": to_int(count_before(soup, "/following")),
"followers": to_int(count_before(soup, "/verified_followers")),
"posts": to_int(posts_match.group(1)) if posts_match else None,
"avatar_url": avatar["src"] if avatar else None,
"banner_url": banner["src"] if banner else None,
}
with open("profile.json", "w", encoding="utf-8") as f:
json.dump(profile, f, ensure_ascii=False, indent=2)
print(json.dumps(profile, ensure_ascii=False, indent=2))
Sample output for x.com/NatGeo:
{
"name": "National Geographic",
"handle": "NatGeo",
"verified": true,
"bio": "Step into wonder and find your inner explorer with National Geographic 🌎",
"location": "Global",
"website": "nationalgeographic.com",
"website_tco": "https://t.co/1kQE47ceZW",
"joined": "November 2008",
"following": 178,
"followers": 28000000,
"posts": 73700,
"avatar_url": "https://pbs.twimg.com/profile_images/2050149546685022208/72MxNUv-_400x400.jpg",
"banner_url": "https://pbs.twimg.com/profile_banners/17471979/1789591798/1500x500"
}
How Do You Scrape a Tweet and Its Replies?
A post page uses the same <article> markup. The first article is the post itself, and the ones after it are the replies X shows logged-out. X shows a few top replies to logged-out visitors, not the whole conversation.
The script also calls oEmbed, X's official embed endpoint. It needs no key, and X's docs list it as not rate limited. It returns the author name, the post text and ready-made embed HTML, which makes it a cheap way to confirm a post still exists.
# pip install requests beautifulsoup4
import json
import os
import re
import sys
import requests
from bs4 import BeautifulSoup
SCRAPE_DO_TOKEN = os.environ.get("SCRAPE_DO_TOKEN", "<your_token>")
POST_URL = sys.argv[1] if len(sys.argv) > 1 else "https://x.com/NatGeo/status/2124548463689974189"
METRIC_RE = re.compile(r"([\d,]+) (replies|reply|reposts|repost|likes|like|bookmarks|bookmark|views|view)\b")
def fetch(url):
response = requests.get(
"https://api.scrape.do/",
params={"token": SCRAPE_DO_TOKEN, "url": url},
timeout=60,
)
response.raise_for_status()
return BeautifulSoup(response.text, "html.parser")
def parse_metrics(label):
metrics = {}
for value, name in METRIC_RE.findall(label or ""):
key = {"reply": "replies", "repost": "reposts", "like": "likes", "bookmark": "bookmarks", "view": "views"}.get(name, name)
metrics[key] = int(value.replace(",", ""))
return metrics
def parse_article(article):
link = next((a for a in article.select('a[href*="/status/"]') if re.search(r"/status/\d+$", a["href"])), None)
handle = next((s.get_text(strip=True) for s in article.select("a span") if s.get_text(strip=True).startswith("@")), None)
text = article.select_one("div[lang]")
group = article.select_one('div[role="group"][aria-label]')
return {
"url": "https://x.com" + link["href"] if link else None,
"handle": handle,
"text": text.get_text(" ", strip=True) if text else None,
**parse_metrics(group["aria-label"] if group else ""),
}
soup = fetch(POST_URL)
articles = [a for a in soup.select("article") if not a.find_parent("article")]
if not articles:
raise SystemExit("No post found: deleted, protected, or behind the login wall")
# The first article is the post itself; the rest are the replies X shows logged-out
post = parse_article(articles[0])
post["replies_shown"] = [parse_article(a) for a in articles[1:]]
# oEmbed is X's official, keyless embed endpoint: a cheap cross-check of author and text
oembed = requests.get("https://publish.x.com/oembed", params={"url": POST_URL, "omit_script": "1"}, timeout=30)
if oembed.ok:
post["oembed_author"] = oembed.json().get("author_name")
with open("post.json", "w", encoding="utf-8") as f:
json.dump(post, f, ensure_ascii=False, indent=2)
print(json.dumps(post, ensure_ascii=False, indent=2))
Pass any post URL as the first argument. Here is the output for the default NatGeo post, trimmed to the first reply, with the reply text shortened (the replies are NatGeo's own thread):
{
"url": "https://x.com/NatGeo/status/2124548463689974189",
"handle": "@NatGeo",
"text": "In this image from our Pictures of the Year 2026, Nat Geo photographer Brent Stirton captured Frankie and Joey Druffel playing among the compost mounds on their family’s farm.",
"replies": 20,
"reposts": 34,
"likes": 225,
"bookmarks": 15,
"views": 47740,
"replies_shown": [
{
"url": "https://x.com/NatGeo/status/2124548468916072759",
"handle": "@NatGeo",
"text": "Their dad, Allen, uses modernized herbicide- and pesticide-free farming methods...",
"replies": 2,
"likes": 15,
"views": 2447
}
],
"oembed_author": "National Geographic"
}
In this script, a metric that is missing from a reply means X showed it as zero.
How Do You Scrape Many Twitter Profiles at Once?
For a list of accounts, run the requests in parallel. This script fetches a list of profiles, 4 at a time, and reports the status, post count, time and credit cost of each:
# pip install requests beautifulsoup4
import os
import time
from concurrent.futures import ThreadPoolExecutor
import requests
from bs4 import BeautifulSoup
SCRAPE_DO_TOKEN = os.environ.get("SCRAPE_DO_TOKEN", "<your_token>")
HANDLES = ["NASA", "BBCWorld", "nytimes", "Reuters", "SpaceX", "verge",
"github", "Google", "Microsoft", "nike", "espn", "NatGeo"]
def scrape_profile(handle):
started = time.time()
response = requests.get(
"https://api.scrape.do/",
params={"token": SCRAPE_DO_TOKEN, "url": f"https://x.com/{handle}"},
timeout=60,
)
soup = BeautifulSoup(response.text, "html.parser")
posts = [a for a in soup.select("article") if not a.find_parent("article")]
return {
"handle": handle,
"status": response.status_code,
"posts": len(posts),
"seconds": round(time.time() - started, 1),
"credits": response.headers.get("scrape.do-request-cost"),
}
# 4 requests at a time; stay within the concurrency your plan allows
with ThreadPoolExecutor(max_workers=4) as pool:
results = list(pool.map(scrape_profile, HANDLES))
for row in results:
print(row)
ok = sum(1 for row in results if row["status"] == 200 and row["posts"] > 0)
print(f"{ok} of {len(results)} profiles returned posts")
In our tests, every profile in the list returned its posts from a plain request.
To run this at scale:
- Detect the login wall. Scrape.do returns the final URL in the
scrape.do-resolved-urlresponse header. If it contains/i/jf/onboarding/, X sent you to the login page. A page with zero articles and no redirect means X changed its markup. Log both cases instead of saving an empty row. - Retry failures with backoff. Our guide to retrying failed Python requests has a ready-made pattern, and handling rate limits covers pacing.
- Scrape on a schedule to build history. Each run returns the latest posts and the current counts, so a daily run builds a time series of followers and engagement.
What If You Need More Than X Shows Logged-Out?
| You need | Use |
|---|---|
| Older posts or a full timeline | The X API, billed per post read |
| Search results or hashtags | The X API |
| Follower lists | The X API |
| Metrics for posts you already know | Scrape each post URL, 1 request per post |
| An embed or a quick existence check | oEmbed, free and keyless |
For a similar public-data workflow on another platform, see how to scrape Reddit.
Is It Still Possible to Scrape Twitter?
X made its public pages easier to scrape and its private ones harder to reach. Profile and post pages need one plain request and a few stable selectors. Search, followers, trends and older posts stay behind the login wall, where the X API is the way in.
If a script returns nothing, check whether X redirected you to login before you touch the selectors.
Create a free Scrape.do account and run your first X profile with the free credits.
Frequently Asked Questions About Twitter Scraping
Do You Need JavaScript Rendering to Scrape X?
No. X sends profile and post pages as full HTML, and a rendered request returned the same posts as a plain one, at a higher credit cost.
Can You Get Older Tweets Without Logging In?
No. Each profile shows its latest few posts to logged-out visitors, and scrolling in a rendered browser loaded no more. For older posts, use the X API, or scrape post URLs you already have one by one.
Why Does My Old Twitter Scraper Return Nothing?
Most older scrapers wait for or select data-testid attributes such as article[data-testid="tweet"]. X's logged-out pages no longer have any, so those selectors match nothing. Switch to the hooks in the tables above: <article>, div[lang] and the engagement bar's aria-label.
Is Scraping X.com Different from Scraping Twitter.com?
No. A request to twitter.com/NatGeo lands on x.com/NatGeo, so you get the same page.
Is It Legal to Scrape Twitter?
Yes. Scraping data that anyone can see without logging in is legal, and three US decisions back it:
- hiQ Labs v. LinkedIn (9th Cir., April 18, 2022). The court affirmed an injunction that stopped LinkedIn from blocking hiQ's access to public profiles. It held that hiQ had raised a serious question that the Computer Fraud and Abuse Act's "without authorization" does not apply where no authorization is generally required, as with public pages (opinion). In a later ruling in November 2022, the district court found hiQ in breach of LinkedIn's User Agreement and granted LinkedIn summary judgment over fake profiles that hiQ's contractors created and logged in with (report).
- Meta Platforms v. Bright Data (N.D. Cal., January 23, 2024). The court held that Facebook's and Instagram's terms "do not apply to and prohibit Bright Data's scraping of publicly available data while logged off" and granted Bright Data summary judgment on Meta's breach of contract claims (order).
- X Corp. v. Bright Data (N.D. Cal., May 9, 2024). The court dismissed X's complaint. It held that X's state-law claims based on scraping and selling data were preempted by the Copyright Act, and that its claims based on access to its servers were too conclusory. X was allowed to seek leave to amend (order).
The common thread is the login. The losses came with accounts and logins, while logged-out scraping of public data held up. The scrapers above never log in.
Legal also covers what you do with the data. Profile data is personal data under the GDPR and similar laws, so keep only the fields you need, store them securely and delete them when you are done. For the general checks, see our guide to checking if a website allows scraping.
How Do You Avoid the X Login Wall When Scraping?
You don't need to. The pages X shows logged-out (profiles, single posts and oEmbed) carry the data this guide scrapes, and everything else redirects to the login page. Use no login and no account automation: that keeps your scraper on the public side.

Web Scraping Expert

