Twitter (X) with Playwright in 2026: What a Browser Script Gets, and the JSON Route in Python and Node

By TwitterAPI.io Team•14 min read
Diagram comparing two routes to X posts: a Playwright browser script that logs in, opens a profile, scrolls and parses, and an API route that sends one request per page of 20 posts and follows next_cursor
Two routes to the same posts. The API route in our run: 738 posts, 44 requests, $0.12 (collected in 2026).
TL;DR
  • Logged out, x.com shows only the top of a profile and a sign-in prompt; scrolling a timeline, search and replies need a logged-in session, which is the account X holds responsible.
  • X's Terms (effective October 9, 2026) prohibit crawling or scraping without prior written consent, and access other than through X's published interfaces.
  • Intercepting responses with page.on("response") gives cleaner data than DOM parsing, but those responses come from undocumented internal endpoints that can change without notice.
  • Our study: /twitter/user/last_tweets returned 738 posts from five organization timelines in 44 requests for $0.12 (collected in 2026).
  • Structure arrives as fields: 58.4% of posts carried links, 39.2% media, 31.2% link cards, and every video listed its MP4 variants (median 5).
  • Already on Playwright? playwright.request.new_context() calls a JSON API with no browser download; Python and Node examples below.

This guide is about plain Playwright scripts, in Python and in Node.js, pointed at x.com. If you drive a browser from Scrapy through scrapy-playwright, our Scrapy guide covers that setup; if you use Selenium, the Selenium guide covers its waits and drivers. Here the focus is the two techniques Playwright users actually reach for on X (DOM locators and listening to network responses), what each one depends on, and how a Playwright project can fetch the same posts as JSON.

We did not run Playwright against x.com for this page, and we do not publish instructions for logging a script into an X account. What follows is built from Playwright's own documentation, X's published Terms and robots.txt, and a study we ran on the API side: five organization timelines, 738 posts, every number measured.

The short version: Playwright is excellent at what it was built for, testing and automating web apps you control or may automate. On X it acts as a logged-in user under X's terms, it is slow because it waits for rendering, and it breaks when the interface changes. If what you need is the data, a JSON endpoint is the shorter path.

Posts returned from five organization timelines by 44 API requests, no browser or X account (collected in 2026)

738 posts for $0.12

01 — Section

What a Playwright script gets from x.com in 2026

Playwright launches a real Chromium, Firefox or WebKit browser, so it sees exactly what a person with the same session would see. That is the whole point of a browser automation tool, and it is also the limit on X.

Logged out. On June 30, 2023 X stopped serving timelines to logged-out visitors; Elon Musk replied the same day that it was a "Temporary emergency measure" because "We were getting data pillaged so much that it was degrading service for normal users!" The restriction never fully went away. When our Selenium guide loaded one public profile logged out, the page held 5 posts and then a "Log in or sign up for X" panel. A Playwright script starting from the same URL starts from the same sliver.

Logged in. With a session, the web app renders a timeline that grows as you scroll, plus search, replies and follower lists. Every one of those requests is made as the account that is logged in. That account, not the script, is what X rate-limits, challenges or suspends.

robots.txt. The current x.com/robots.txt gives Googlebot and Bingbot named groups, blocks several AI and social crawlers outright, and ends with a catch-all group User-agent: * followed by Disallow: /, plus Crawl-delay: 1. A Playwright script is not one of the named crawlers.

Target on x.comLogged outLogged in (as your account)
Profile header (bio, counts)ShownShown
Recent posts on a profileA few, then a sign-in promptLoads more on scroll
Search resultsSign-in promptLoads more on scroll
Replies under a postSign-in promptLoads more on scroll
02 — Section

Two Playwright techniques on X: DOM locators vs network responses

Playwright tutorials for X usually take one of two routes. Both are standard Playwright features; the difference is what you parse.

DOM locators. You scroll with page.mouse.wheel(delta_x, delta_y), which Playwright's docs describe as dispatching a wheel event "usually used to manually scroll the page", wait for new post cards, and read text and counts with locators. This is the slowest and least stable option: X's markup is generated by a React app, counts are abbreviated for display ("1.2K"), and quoted posts, link cards and videos are nested components you have to reassemble.

Network responses. Playwright can watch every response the page receives: page.on("response", ...) for all of them, or page.expect_response(pattern) to wait for one after an action, per the Network page of the Playwright docs. On X, the web app fetches post data as JSON in background requests, so a listener can pick up structured objects instead of scraping HTML. It is cleaner than DOM parsing, but those requests belong to X's internal web client: they are not a published API, their names and shapes are undocumented, and they change when X ships a new web build.

What both share. Either way you are reading X through its web client, as an account, at the speed of a browser. X's Terms (effective October 9, 2026, at x.com/en/tos) prohibit accessing the Services "by any means (automated or otherwise) other than through our currently available, published interfaces" and state that "crawling or scraping the Services in any form, for any purpose without our prior written consent is expressly prohibited." The same Terms set liquidated damages of $15,000 per 1,000,000 posts for requesting, viewing or accessing more than 1,000,000 posts in any 24-hour period in violation of them.

ApproachWhat you parseBreaks whenAccount needed
Playwright + locatorsRendered HTMLMarkup or layout changesYes, past the first posts
Playwright + page.on("response")X's internal JSONInternal endpoints or shapes changeYes
Published JSON APIDocumented JSON fieldsVersioned API changesNo, for reads
03 — Section

Logged-in sessions, storage_state, and what X's Terms mean for the account

Every logged-in Playwright recipe for X ends up at the same feature: saving a session with browser_context.storage_state() and loading it into later contexts, so the script does not log in each time. Playwright's authentication docs describe it for test suites, and they come with a warning worth quoting in full: "The browser state file may contain sensitive cookies and headers that could be used to impersonate you or your test account." The docs add: "We strongly discourage checking them into private or public repositories."

What that file is on X. A saved X session is the account itself. Anyone with the file can act as it, and anything the script does is done by that account. Our Twitter cookie guide explains what the session cookies are and why they should be treated like a password.

What happens to the account. X decides whether a session behaves like automation. The common sign is the message "This request looks like it might be automated" (error 226), followed by challenges, temporary locks or suspension. That is X enforcing its rules on an account; it is a signal to stop, and we do not cover ways around it.

Why we do not ship a logged-in x.com script here. It would be a recipe for doing something X's Terms prohibit, with someone's account as the collateral. If you have written permission from X for a specific use, follow the terms of that agreement; otherwise use a published interface, the official X API or a third-party API that returns the same public data without your account.

04 — Section

Playwright without a browser: calling the API with APIRequestContext (Python)

Many Playwright users already have the library in their project for end-to-end tests. Playwright includes an HTTP client for exactly this kind of call: APIRequestContext, created with playwright.request.new_context(...), documented on Playwright's API testing page. It sends requests directly, shares nothing with a browser, and returns a response with .ok, .status and .json().

What we ran. In a fresh Python virtual environment we installed playwright from PyPI (version 1.60.0, the newest release that installs on that machine's Python 3.9; the latest, 1.65.3, requires Python 3.10 or newer per its PyPI metadata). We did not run playwright install, so no browser binaries were present, and a request.new_context() GET against a public PyPI JSON URL returned HTTP 200 and parsed JSON. We also confirmed from the installed package that new_context accepts extra_http_headers and timeout and that get accepts params. The example below uses only those.

What the example does. It pages through /twitter/user/last_tweets with the X-API-Key header, follows next_cursor until has_next_page is false, checks status on every page (errors carry their text in msg), and pauses a fixed 5 seconds between pages, which fits the 0.2 requests per second that applies before the first payment. After the first payment the limit is 20 requests per second, so the pause can drop to a fraction of a second.

Why this beats a browser for data. One request returns up to 20 posts with every count, media variant and quoted post already parsed. There is no rendering to wait for, no scroll loop, and nothing tied to X's markup.

python
# pip install playwright   (no "playwright install" needed: APIRequestContext launches no browser)
import os
import time

from playwright.sync_api import sync_playwright

BASE = "https://api.twitterapi.io"


def timeline(user_name, max_pages=10):
    posts = []
    with sync_playwright() as p:
        api = p.request.new_context(
            extra_http_headers={"X-API-Key": os.environ["TWITTERAPI_IO_API_KEY"]},
            timeout=30000,
        )
        cursor = ""
        for _ in range(max_pages):
            r = api.get(f"{BASE}/twitter/user/last_tweets",
                        params={"userName": user_name, "cursor": cursor})
            if not r.ok:
                raise RuntimeError(f"HTTP {r.status}: {r.text()[:200]}")
            body = r.json()
            if body.get("status") != "success":
                raise RuntimeError(body.get("msg"))
            posts.extend((body.get("data") or {}).get("tweets") or [])
            if not body.get("has_next_page") or not body.get("next_cursor"):
                break
            cursor = body["next_cursor"]
            time.sleep(5)  # fixed pacing for the 0.2 requests/s pre-payment limit
        api.dispose()
    return posts


posts = timeline("playwrightweb")
print(len(posts), "posts;", sum(1 for t in posts if t.get("extendedEntities")), "with media")
05 — Section

The same in Node.js, and the versions to pin

Playwright's Node package exposes the same client as request.newContext(). Per the Playwright docs for APIRequest, extraHTTPHeaders is "an object containing additional HTTP headers to be sent with every request". The response methods are calls in Node (res.ok(), res.status()), unlike the Python properties.

PackageLatest releaseRuntime requirementLicense
playwright on PyPI1.65.3Python 3.10+Apache-2.0 (GitHub repo)
playwright on npm1.65.2Node.js 20+Apache-2.0

Note on versions. Versions above were read from the PyPI and npm registries while writing this guide. Playwright releases often; pin the version in requirements.txt or package.json rather than copying these numbers.

Same rules apply. Keep the API key in an environment variable, check status as well as the HTTP code, and keep a fixed pace between pages. The code below is an ES module (.mjs, or "type": "module" in package.json) so top-level await works.

javascript
// npm i playwright   (Node 20+; the request context needs no browser download)
import { request } from 'playwright';

const BASE = 'https://api.twitterapi.io';

async function timeline(userName, maxPages = 10) {
  const api = await request.newContext({
    extraHTTPHeaders: { 'X-API-Key': process.env.TWITTERAPI_IO_API_KEY },
  });
  const posts = [];
  let cursor = '';
  for (let i = 0; i < maxPages; i++) {
    const res = await api.get(`${BASE}/twitter/user/last_tweets`, {
      params: { userName, cursor },
    });
    if (!res.ok()) throw new Error(`HTTP ${res.status()}: ${(await res.text()).slice(0, 200)}`);
    const body = await res.json();
    if (body.status !== 'success') throw new Error(body.msg);
    posts.push(...(body.data?.tweets ?? []));
    if (!body.has_next_page || !body.next_cursor) break;
    cursor = body.next_cursor;
    await new Promise((r) => setTimeout(r, 5000)); // fixed pacing
  }
  await api.dispose();
  return posts;
}

const posts = await timeline('playwrightweb');
console.log(posts.length, 'posts; first:', posts[0]?.url);
06 — Section

Our study: 738 posts from five organization timelines

To put numbers on the API route, we fetched the latest posts of five organization accounts from the browser and developer-tools world: Playwright's own account @playwrightweb, Visual Studio Code (@code), TypeScript (@typescript), Chrome for Developers (@ChromiumDev) and Firefox (@firefox). Each account got up to 10 pages of /twitter/user/last_tweets (about 200 posts), default settings, so replies were not included.

Totals. 44 timeline requests returned 738 posts, 16.8 posts per request on average. The run cost 12,015 credits, $0.12, and the wall time across the five accounts was 151 seconds.

Where timelines ended. @code and @ChromiumDev filled all 10 pages. The other three ended earlier, with has_next_page false: @playwrightweb at 106 posts (its profile reports 163 in statusesCount), @typescript at 132 (428), and @firefox at 100 (51,029). statusesCount counts every post the account ever made, including replies, which this call excludes by default; we did not investigate the rest of the gap. Plan for a timeline to end before the profile count suggests, and add includeReplies=true if you need replies.

AccountRequestsPostsWall timeStopped at
@playwrightweb810626 send of timeline
@code1020036 s10-page cap
@typescript913233 send of timeline
@ChromiumDev1020033 s10-page cap
@firefox710023 send of timeline

About the timing. Our client is rate-limited to 5 requests per second for the whole machine, and other jobs shared that limit during the run, so the 3.43 seconds per request we measured includes waiting for our own lock. Treat it as an upper bound, not API latency. We did not time a Playwright run against x.com, so this page makes no claim about how long a browser takes for the same posts.

Horizontal bar chart of posts returned per account: playwrightweb 106, code 200, typescript 132, ChromiumDev 200, firefox 100, with requests and wall time for each
Posts returned by /twitter/user/last_tweets per account, up to 10 pages each: 738 posts in 44 requests (collected in 2026).
07 — Section

What arrives as JSON fields, and the DOM work it replaces

The second half of the study asked a Playwright-specific question: how much of each post is nested structure that a DOM scraper has to reassemble from rendered components? Across the 738 posts, the API returned it as fields.

What the post containsShare of postsJSON field
At least one link58.4%entities.urls[] (expanded URL)
Photo, video or GIF39.2%extendedEntities.media[]
Link preview card31.2%card
Video or GIF with MP4 variants24.8%media[].video_info.variants[]
Repost of another account22.2%retweeted_tweet
Quote of another post7.0%quoted_tweet

Counts as integers. viewCount, bookmarkCount, likeCount, replyCount, quoteCount, createdAt and conversationId were present on 100% of posts. On a rendered page the same counts appear abbreviated, and the timestamp is a relative label. The median view count on original (non-repost) posts in the sample was 26,887; a rendered page shows a number like that in abbreviated form, so a locator gets a rounded label instead of the value.

Video. Each video listed a median of 5 variants (up to 6) with bitrate and content type, so picking the highest-quality MP4 is a max() over a list, as in the code at the end of this guide. In a browser the player streams segments and the file URLs are not in the markup.

Breadth. Every post object carried 31 top-level keys, including the author object with follower counts, so one request also gives you the account context a scraper would need a second page load for.

Bar chart of the share of 738 posts carrying each structure: links 58.4%, media 39.2%, link cards 31.2%, video or GIF variants 24.8%, reposts 22.2%, quoted posts 7.0%
Nested structures as JSON fields across 738 posts from five organization timelines (collected in 2026).
08 — Section

Cost: Playwright is free to run, the data is not

Playwright itself is open source (Apache-2.0) and costs nothing. The costs of a Playwright scraper on X are elsewhere: an X account that carries the risk, machines that run full browsers, the time a browser spends rendering and scrolling, and the maintenance each time X changes its web client.

On this API. Timeline reads cost 15 credits per post returned, which is $0.15 per 1,000 posts, with a minimum of 15 credits per request, so an empty page costs $0.00015 and a full page of 20 posts $0.003. Profile lookups cost 18 credits per user, $0.18 per 1,000. Reads need no X account. New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); the current amount is on the pricing page.

On the official X API. The pay-per-usage rate card at docs.x.com/x-api/getting-started/pricing lists $0.005 per post read, $0.010 per user read and $0.010 per follower or following read, with pay-per-usage capped at 3 million post reads per monthly billing cycle and an Enterprise plan above that. Per 1,000 posts that is $5 against $0.15, about 33 times more.

Same jobThis APIOfficial X API
Our run: 738 posts$0.12$3.69
1,000 posts$0.15$5.00
1,000 profiles$0.18$10.00

When Playwright is still the right tool. Testing your own web app, including any X embed or share button on it; automating sites whose terms allow it; and screenshots of public pages you are permitted to capture. For collecting posts from X, use a published interface.

09 — Section

How we collected this

Question. For a Playwright user who wants a profile's recent posts, how many requests, how much time and money does the JSON route take, and what structure comes back as fields that a browser script would otherwise parse?

Accounts. Five organization accounts: @playwrightweb, @code, @typescript, @ChromiumDev and @firefox. Organization accounts only.

Method and window. /twitter/user/last_tweets with userName, default includeReplies (false), newest first, up to 10 pages per account, plus one /twitter/user/info call per account for statusesCount. The window is each account's latest posts at collection time, collected in 2026. Sample: 738 posts from 44 timeline requests. Wall time was measured around each account's run and includes waits on a rate limiter shared with other jobs.

What the sample cannot show. Five developer-tool organizations do not represent X as a whole; media and link shares will differ for news, personal or brand accounts. We did not run Playwright or any browser against x.com, so the page reports no browser timings, success rates or block rates, and describes the browser approach from Playwright's documentation and X's published documents.

Privacy. Aggregates only. We did not analyze the authors of reposted or quoted posts. The de-identified sample rows contain no post ids, URLs, text or handles.

python
"""timeline_to_csv.py - fetch an X (Twitter) profile's recent posts as JSON and save a CSV.
The data a Playwright script would scroll and parse for, without a browser or an X account.

    pip install requests
    export TWITTERAPI_IO_API_KEY=...   # from the twitterapi.io dashboard
    python timeline_to_csv.py playwrightweb 200
"""
import csv
import os
import sys
import time

import requests

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_API_KEY"]}
PAUSE_S = 5  # fixed pacing: 0.2 requests/s applies before the first payment


def fetch_posts(user_name, limit=200):
    posts, cursor = [], ""
    while len(posts) < limit:
        r = requests.get(
            f"{BASE}/twitter/user/last_tweets",
            headers=HEADERS,
            params={"userName": user_name, "cursor": cursor},
            timeout=30,
        )
        r.raise_for_status()
        body = r.json()
        if body.get("status") != "success":
            raise RuntimeError(body.get("msg"))
        posts.extend((body.get("data") or {}).get("tweets") or [])
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
        time.sleep(PAUSE_S)
    return posts[:limit]


def to_row(t):
    media = (t.get("extendedEntities") or {}).get("media") or []
    videos = [m for m in media if m.get("type") in ("video", "animated_gif")]
    best_mp4 = ""
    for m in videos:
        mp4s = [v for v in (m.get("video_info") or {}).get("variants") or []
                if v.get("content_type") == "video/mp4"]
        if mp4s:
            best_mp4 = max(mp4s, key=lambda v: v.get("bitrate") or 0)["url"]
    return {
        "id": t["id"],
        "url": t["url"],
        "createdAt": t["createdAt"],
        "text": t["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"),
        "bookmarks": t.get("bookmarkCount"),
        "is_repost": t.get("retweeted_tweet") is not None,
        "quoted_url": (t.get("quoted_tweet") or {}).get("url"),
        "links": " ".join(u.get("expanded_url", "") for u in (t.get("entities") or {}).get("urls") or []),
        "media_types": " ".join(m.get("type", "") for m in media),
        "best_mp4": best_mp4,
    }


if __name__ == "__main__":
    user = sys.argv[1] if len(sys.argv) > 1 else "playwrightweb"
    limit = int(sys.argv[2]) if len(sys.argv) > 2 else 200
    rows = [to_row(t) for t in fetch_posts(user, limit)]
    if rows:
        with open(f"{user}_posts.csv", "w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=list(rows[0]))
            w.writeheader()
            w.writerows(rows)
    print(f"{len(rows)} posts from @{user} saved")

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

Can Playwright scrape Twitter (X) in 2026?

Technically a Playwright browser can render x.com, but logged out it gets only the top of a profile and a sign-in prompt, so collecting timelines, search or replies means running as a logged-in X account. X's Terms (effective October 9, 2026) prohibit crawling or scraping without prior written consent and access through anything other than X's published interfaces. For post data, a JSON API is the practical route.

Is it better to parse the DOM or intercept network responses with Playwright?

Listening with page.on("response") returns structured JSON instead of abbreviated, rendered text, so it is less fragile than locators. But on X those responses come from the web app's internal, undocumented endpoints, which change without notice, and the session is still a logged-in account under X's Terms. A published API gives the same kind of JSON without either problem.

Should I use Python or Node for Playwright?

Both bindings expose the same features. The latest releases at the time of writing were 1.65.3 on PyPI (Python 3.10+) and 1.65.2 on npm (Node.js 20+). Choose the language the rest of your pipeline uses. For data collection from X, the language matters less than the route: both can call a JSON API with Playwright's APIRequestContext or a plain HTTP client.

Can I reuse my X login with Playwright's storage_state?

Playwright can save and reload a session with storage_state, and its docs warn that the file "may contain sensitive cookies and headers that could be used to impersonate you". On X the saved session is your account: everything the script does is done by it, and X can rate-limit, lock or suspend it. We do not recommend automating x.com with your account.

Does Playwright's APIRequestContext need a browser installed?

No. We installed playwright from PyPI in a fresh virtual environment without running playwright install, and a request.new_context() GET returned HTTP 200 and JSON. It is a plain HTTP client inside Playwright, useful if the library is already in your project.

How many posts does one API request return, and how do I get more?

/twitter/user/last_tweets returns up to 20 posts per page, newest first, with has_next_page and next_cursor. Pass next_cursor as cursor to get the next page. In our study 44 requests returned 738 posts across five accounts; three timelines ended before the 10-page cap.

How much does it cost compared with the official X API?

Timeline reads here cost 15 credits per post returned ($0.15 per 1,000 posts), minimum 15 credits per request. The official X API pay-per-usage rate is $0.005 per post read, $5 per 1,000. Our 738-post run cost $0.12; the same reads on the X API would be $3.69.

What is the rate limit for API calls from a Playwright script?

0.2 requests per second before the first payment, 20 requests per second once paid, 50 on the Scale plan and 500 on Business, with higher limits on request. Keep a fixed pause between pages that fits your limit.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.