# Twitter / X Scraper — Date Filter, Profile & Search (`totaka/twitter-x-scraper`) Actor

Scrape tweets from any Twitter/X profile or keyword search with exact date filtering (since/until), language filter, tweet type filter, and engagement thresholds. Date-accurate via X search operators.

- **URL**: https://apify.com/totaka/twitter-x-scraper.md
- **Developed by:** [Thomas Gharbi](https://apify.com/totaka) (community)
- **Categories:** Social media, Marketing
- **Security:** Limited permissions
- **Stats:** 9 total users, 3 monthly users, 0.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Twitter / X Scraper — Date Filter, Profile & Keyword Search

Scrape tweets from **any Twitter/X profile or keyword search** with exact date filtering, language filter, tweet type, and engagement thresholds. Exports to JSON, CSV, or Excel. No Twitter API key required.

***

### Why date filtering actually works here

The #1 complaint about Twitter scrapers: **date filters that return wrong dates**. Most scrapers read the profile timeline — which Twitter shows in a non-chronological order and can't be filtered server-side. You ask for tweets from 2023 and get random results from 2019 to today.

This scraper uses **X's search engine** instead of the timeline. Every request uses `from:handle since:YYYY-MM-DD until:YYYY-MM-DD` operators — the same approach X's own Advanced Search uses. Dates are enforced server-side before any results are returned.

The difference: `from:elonmusk since:2024-01-01 until:2024-03-31` will only return tweets from that exact window, every single time.

***

### Input parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `handles` | array | Twitter/X handles to scrape (without @) |
| `searchTerms` | array | Free-text search queries (supports all X operators) |
| `maxTweetsPerHandle` | integer | Max tweets per handle or search term (default: 100) |
| `since` | string | Start date — YYYY-MM-DD format |
| `until` | string | End date — YYYY-MM-DD format |
| `tweetTypes` | array | Filter by type: `original`, `reply`, `retweet`, `quote` |
| `lang` | string | Language code: `en`, `fr`, `es`, `de`, etc. |
| `minLikes` | integer | Minimum like count |
| `minRetweets` | integer | Minimum retweet count |
| `twitterAuthToken` | string | Your X auth_token cookie (required for login-protected content) |
| `twitterCt0` | string | Your X ct0 CSRF cookie (required together with auth_token) |
| `proxyConfiguration` | object | Proxy settings (residential recommended) |

#### Profile scraping example

```json
{
  "handles": ["elonmusk", "sama"],
  "maxTweetsPerHandle": 200,
  "since": "2024-01-01",
  "until": "2024-06-30",
  "tweetTypes": ["original"],
  "lang": "en",
  "minLikes": 100
}
```

#### Keyword search example

```json
{
  "searchTerms": [
    "ChatGPT site:techcrunch.com",
    "#bitcoin lang:en min_faves:500",
    "from:openai -filter:retweets"
  ],
  "maxTweetsPerHandle": 500,
  "since": "2024-03-01",
  "until": "2024-03-31"
}
```

***

### Output fields

Each tweet is saved as one item in the dataset:

| Field | Type | Description |
|-------|------|-------------|
| `tweetId` | string | Unique tweet ID |
| `url` | string | Direct URL to the tweet on X.com |
| `createdAt` | string | ISO 8601 timestamp |
| `fullText` | string | Full tweet text (no truncation) |
| `tweetType` | string | `original`, `reply`, `retweet`, or `quote` |
| `metrics.likes` | integer | Like count |
| `metrics.retweets` | integer | Retweet count |
| `metrics.replies` | integer | Reply count |
| `metrics.bookmarks` | integer | Bookmark count |
| `metrics.views` | integer | View count |
| `author.handle` | string | Twitter handle |
| `author.displayName` | string | Display name |
| `author.verified` | boolean | Legacy verified badge |
| `author.blueVerified` | boolean | Blue checkmark (paid) |
| `media` | array | Photos/videos `[{type, url, thumbnailUrl}]` |
| `hashtags` | array | Hashtags without # |
| `mentions` | array | Mentioned handles without @ |
| `links` | array | External URLs |
| `replyToHandle` | string|null | Handle being replied to |
| `quotedTweet` | object|null | Quoted tweet content |
| `searchQuery` | string | X search query used |
| `scrapedAt` | string | Scrape timestamp (ISO 8601) |

#### Output example

```json
{
  "tweetId": "1769432156789012345",
  "url": "https://x.com/elonmusk/status/1769432156789012345",
  "createdAt": "2024-03-17T18:42:00.000Z",
  "fullText": "The thing I find most surprising is how quickly people adapt to new technology.",
  "tweetType": "original",
  "metrics": {
    "likes": 54200,
    "retweets": 6100,
    "replies": 4300,
    "bookmarks": 15000,
    "views": 8400000
  },
  "author": {
    "handle": "elonmusk",
    "displayName": "Elon Musk",
    "profileUrl": "https://x.com/elonmusk",
    "avatarUrl": "https://pbs.twimg.com/profile_images/...",
    "verified": false,
    "blueVerified": true
  },
  "media": [],
  "hashtags": [],
  "mentions": [],
  "links": [],
  "replyToHandle": null,
  "quotedTweet": null,
  "searchQuery": "from:elonmusk since:2024-03-01 until:2024-04-01",
  "targetHandle": "elonmusk",
  "scrapedAt": "2024-06-01T12:00:00.000Z"
}
```

***

### Use cases

**Brand monitoring** — Collect every mention of your brand, product, or competitor over a precise date window. Feed the results into a sentiment analysis pipeline or track share-of-voice over time.

**Influencer research** — Analyze a creator's posting frequency, engagement rate, and topic mix for any time period before signing a partnership.

**Market research** — Track how conversations around a product category or trend evolve week by week.

**Academic & journalism research** — Reproduce a dataset from a specific news event with exact date bounds. Results are deterministic — the same query always returns the same tweets.

**AI training data** — Export large volumes of tweets on a topic as training or fine-tuning data for LLMs.

**Social media analytics** — Build dashboards showing tweet volume, engagement trends, and top content for any account.

**Competitor analysis** — Monitor what a competitor's customers are saying, what complaints recur, and how the brand responds.

***

### Authentication

X (Twitter) shows a login wall for most search results since 2023. To bypass it, provide your account cookies:

1. Open [x.com](https://x.com) in Chrome and log in
2. Open DevTools → Application → Cookies → x.com
3. Copy the value of `auth_token` and `ct0`
4. Paste them into the `twitterAuthToken` and `twitterCt0` inputs

These cookies grant the scraper the same access as your logged-in session. Use a secondary account if preferred.

***

### Limitations

- **Login required** for search results — provide `twitterAuthToken` + `ct0` cookies
- **Private accounts** cannot be scraped
- **Rate limits** apply — very high volumes may require multiple runs
- **Very old tweets** (pre-2010) may not be indexed in X's search

***

### Support

Found a bug or need help? Open a ticket in the **Issues tab** on the actor page. We respond to every issue and ship fixes quickly.

# Actor input Schema

## `handles` (type: `array`):

List of Twitter/X handles to scrape (e.g. \["elonmusk", "openai"]). Do not include @.

## `searchTerms` (type: `array`):

Search keywords or advanced queries (e.g. \["ChatGPT AI", "#bitcoin lang:en"]).

## `maxTweetsPerHandle` (type: `integer`):

Maximum number of tweets to collect per handle or keyword search.

## `since` (type: `string`):

Only collect tweets on or after this date. Uses Twitter's since: operator — exact and reliable.

## `until` (type: `string`):

Only collect tweets on or before this date. Uses Twitter's until: operator.

## `tweetTypes` (type: `array`):

Which tweet types to include in output.

## `includeRetweets` (type: `boolean`):

Include retweets in results.

## `includeReplies` (type: `boolean`):

Include reply tweets in results.

## `lang` (type: `string`):

Filter tweets by language code. Leave empty for all languages.

## `minLikes` (type: `integer`):

Only collect tweets with at least this many likes.

## `minRetweets` (type: `integer`):

Only collect tweets with at least this many retweets.

## `twitterAuthToken` (type: `string`):

Your X/Twitter auth_token cookie value (required to bypass login wall). In Chrome: DevTools → Application → Cookies → x.com → auth_token.

## `twitterCt0` (type: `string`):

Your X/Twitter ct0 cookie value (CSRF token). Required together with auth_token.

## `proxyConfiguration` (type: `object`):

Residential proxies strongly recommended for Twitter/X.

## Actor input object example

```json
{
  "handles": [
    "elonmusk"
  ],
  "maxTweetsPerHandle": 100,
  "tweetTypes": [
    "original",
    "reply",
    "retweet",
    "quote"
  ],
  "includeRetweets": true,
  "includeReplies": true,
  "minLikes": 0,
  "minRetweets": 0,
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ]
  }
}
```

# Actor output Schema

## `results` (type: `string`):

Dataset containing all scraped tweets. Each item includes tweetId, url, createdAt, fullText, tweetType (original/reply/retweet/quote), metrics (likes, retweets, replies, bookmarks, views), author info, media, hashtags, mentions, and links.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "handles": [
        "elonmusk"
    ],
    "maxTweetsPerHandle": 100,
    "tweetTypes": [
        "original",
        "reply",
        "retweet",
        "quote"
    ],
    "proxyConfiguration": {
        "useApifyProxy": true,
        "apifyProxyGroups": [
            "RESIDENTIAL"
        ]
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("totaka/twitter-x-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "handles": ["elonmusk"],
    "maxTweetsPerHandle": 100,
    "tweetTypes": [
        "original",
        "reply",
        "retweet",
        "quote",
    ],
    "proxyConfiguration": {
        "useApifyProxy": True,
        "apifyProxyGroups": ["RESIDENTIAL"],
    },
}

# Run the Actor and wait for it to finish
run = client.actor("totaka/twitter-x-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "handles": [
    "elonmusk"
  ],
  "maxTweetsPerHandle": 100,
  "tweetTypes": [
    "original",
    "reply",
    "retweet",
    "quote"
  ],
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ]
  }
}' |
apify call totaka/twitter-x-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,totaka/twitter-x-scraper"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/FbPWdFLjuhNLGxAUU/builds/fwSHjgM49S1g6MYnR/openapi.json
