Skip to main content

🐦 Panen Tweet — Twitter/X Scraper

PyPI version Python 3.7+ License: MIT Changelog

Panen Tweet is a Python tool for scraping tweet data from Twitter/X based on keywords, date ranges, language, and tweet types. Suitable for research, data analysis, or thesis purposes.


📋 Table of Contents


✅ Prerequisites

Before you start, make sure you have:

  • Python 3.7 or newer → Download here
  • Google Chrome installed on your computer
  • An active Twitter/X account

Check your Python version:

python --version

Installation

pip install panen-tweet

Method 2: From Source Code (GitHub)

git clone https://github.com/Dhaniaaa/panen-tweet.git
cd panen-tweet
pip install -e .

Special: Google Colab or Linux Server (VPS)

On Google Colab and Linux servers, Google Chrome is not installed by default. Run these commands first:

# 1. Install the library
!pip install panen-tweet

# 2. Install Google Chrome (only needed once)
!panen-tweet install-chrome

Getting Auth Token

What is an auth_token? An auth token is a unique code that proves you are logged into Twitter/X. This tool needs this token to access tweet data.

How to Get the Token (Step-by-Step):

  1. Open your browser (Chrome or Firefox) and log in to x.com
  2. Press F12 to open Developer Tools
  3. Click the Application tab (Chrome) or Storage tab (Firefox)
  4. In the left panel, click Cookies → select https://x.com
  5. Find the row named auth_token
  6. Click the row, then copy the value in the right column

🖼️ The token looks like a long string of characters, example: 1a2b3c4d5e6f7a8b9c0d...

TOKEN SECURITY — MUST READ!

This token is the full access key to your Twitter/X account.

  • ❌ DO NOT share the token with anyone
  • ❌ DO NOT hardcode the token directly in your Python file
  • ❌ DO NOT commit/push files containing the token to GitHub
  • ✅ Store the token in a .env file (see the guide in SECURITY.md)
  • ✅ If the token is leaked, immediately change your Twitter/X password

Usage

There are 3 ways to use Panen Tweet. Choose the one that best suits your needs.


Method 1: Command Line Interface (CLI) — Easiest for Beginners

After installation, simply run:

panen-tweet

The program will guide you interactively. You will be asked to enter:

No. Question Example Input
1 Auth token (paste token from browser)
2 Search keyword/topic jakarta flood
3 Max tweets per session 100
4 Start date 2024-01-01
5 End date 2024-01-07
6 Interval days per session 1 (1 = per day)
7 Language code id (Indonesian), en (English), or leave blank for all
8 Tweet type 1 (Top) or 2 (Latest)
9 Enable auto-resume? y / n (default n)
10 Download media? y / n (default n)

Example terminal output:

============================================================
       SCRAPE-X - Twitter/X Scraping Tool
============================================================

IMPORTANT: You need the 'auth_token' cookie from your Twitter/X account.
...
Enter your auth_token: <paste_token_here>

============================================================
       SCRAPING CONFIGURATION
============================================================

1. Enter search keyword/topic: jakarta flood
2. What is the MAXIMUM number of tweets to collect PER SESSION? 100
3. Enter overall START DATE (YYYY-MM-DD): 2024-01-01
4. Enter overall END DATE (YYYY-MM-DD): 2024-01-07
5. How many interval days per scraping session? (e.g., 1 for per day): 1
6. Enter language code (e.g., 'id' or 'en', leave blank for all languages): en
7. Select tweet type (1 for Top, 2 for Latest): 2

--- Additional Options ---
Enable Auto-Resume if interrupted? (y/n, default n): y
Download media (images)? (y/n, default n): n

The scraped results will be automatically saved to a CSV file, example: tweets_jakartaflood_latest_20240101-20240107.csv


Method 2: As a Python Library

Suitable if you want to integrate it into your own notebook or script.

from panen_tweet import TwitterScraper
import datetime
import os

# ✅ Safe way: read token from environment variable
# Run this in terminal first: export TWITTER_AUTH_TOKEN="yourtoken"

auth_token = os.getenv('TWITTER_AUTH_TOKEN')

if not auth_token:
    raise ValueError("Token is not set! See SECURITY.md for instructions.")

# Initialize scraper
scraper = TwitterScraper(
    auth_token=auth_token,
    scroll_pause_time=5,  # Pause between scrolls (seconds) - increase if connection is slow
    headless=True         # True = without browser GUI | False = show browser
)

# Run scraping
df = scraper.scrape_with_date_range(
    keyword="jakarta flood",
    target_per_session=100,
    start_date=datetime.datetime(2024, 1, 1),
    end_date=datetime.datetime(2024, 1, 7),
    interval_days=1,
    lang=None,            # Recommended: None for all languages (X's lang: filter often misses recent tweets)
    search_type='latest'  # 'top' or 'latest'
)

# Save to CSV
if df is not None:
    scraper.save_to_csv(df, "scraping_results.csv")
    print(f"✅ Successfully scraped {len(df)} tweets!")
    print(df.head())
else:
    print("❌ No data was successfully scraped.")

Method 3: Using a .env File for Token Security

This method is the safest to store the token without the risk of uploading it to GitHub.

Step 1 — Install python-dotenv:

pip install python-dotenv

Step 2 — Create a .env file in your project folder:

TWITTER_AUTH_TOKEN=your_token_here

Step 3 — Load it in your Python code:

from dotenv import load_dotenv
import os

load_dotenv()  # Read the .env file
auth_token = os.getenv('TWITTER_AUTH_TOKEN')

The .env file is automatically included in .gitignore, so it will not be uploaded to GitHub.

Or if you prefer to use the terminal directly without a .env file:

Windows PowerShell:

$env:TWITTER_AUTH_TOKEN = "your_token_here"
panen-tweet

Linux / Mac:

export TWITTER_AUTH_TOKEN="your_token_here"
panen-tweet

Output Format (CSV)

Scraping results are automatically saved in CSV format with the following columns:

Column Description
username Display name of the user
handle Twitter account name (@username)
timestamp Time the tweet was posted (ISO 8601 format)
tweet_text Text content of the tweet (empty for media-only tweets)
url Direct link to the tweet
reply_count Number of replies
retweet_count Number of retweets
like_count Number of likes
media_urls Media URLs, separated by ; (empty when the tweet has no media)

Example CSV content:

username,handle,timestamp,tweet_text,url,reply_count,retweet_count,like_count,media_urls
Budi Santoso,@budisant,2024-01-01T10:30:00.000Z,"Severe flood in Jakarta!",https://x.com/budisant/status/123,5,10,25,https://pbs.twimg.com/media/ABC123?format=jpg

The CSV is written with a UTF-8 BOM (utf-8-sig) so Excel opens it correctly. The file is appended per session, so a long run keeps adding rows to the same file.


Complete Parameters

TwitterScraper()

TwitterScraper(
    auth_token=None,           # (REQUIRED) Token from browser cookie
    scroll_pause_time=5,       # Pause between scrolls, in seconds (default: 5)
    headless=True,             # True = without browser GUI | False = show browser
    chrome_binary_path=None    # Path to the Chrome/Chromium executable (optional)
)

scrape_with_date_range()

scraper.scrape_with_date_range(
    keyword="",                # (REQUIRED) Search keyword
    target_per_session=100,    # Target number of tweets per session (default: 100)
    start_date=datetime,       # (REQUIRED) Start date, format: datetime(YYYY, M, D)
    end_date=datetime,         # (REQUIRED) End date, format: datetime(YYYY, M, D)
    interval_days=1,           # Interval days per session (1 = scraping per day)
    lang=None,                 # Language code ('en', 'id', etc.) or None (recommended; X's lang: filter can miss recent tweets)
    search_type='top',         # 'top' = top tweets | 'latest' = latest tweets
    resume=False,              # Resume from the last date already in output_filename
    output_filename='scraped_data.csv',  # Where to write the CSV
    download_media=False,      # Download tweet images / video thumbnails
    media_dir='media'          # Folder to store downloaded media
)

Auto-Resume

If a long run is interrupted, restart with resume=True and the same output_filename. The scraper:

  1. Reads the existing CSV and starts from the day after the most recent tweet.
  2. Skips tweets whose URL is already in the file, so no duplicate rows are appended.
  3. Returns a DataFrame containing both the previous rows and the newly scraped ones.
df = scraper.scrape_with_date_range(
    keyword="jakarta flood",
    target_per_session=100,
    start_date=datetime.datetime(2024, 1, 1),
    end_date=datetime.datetime(2024, 1, 30),
    interval_days=1,
    resume=True,
    output_filename="tweets_jakarta.csv",
)

Media Download

Set download_media=True to save tweet images and video thumbnails alongside the CSV. Files keep their original extension (jpg, png, …) and are stored in media_dir.

df = scraper.scrape_with_date_range(
    keyword="jakarta flood",
    target_per_session=50,
    start_date=datetime.datetime(2024, 1, 1),
    end_date=datetime.datetime(2024, 1, 7),
    interval_days=1,
    download_media=True,
    media_dir="media",
)

Tips & Tricks

Collecting Many Tweets

  • Use interval_days=1 to scrape per day for more detailed results
  • Do not set target_per_session too high (recommended 50–200)
  • Increase scroll_pause_time to allow more loading time if your connection is slow

Avoiding Rate Limits

Rate limits mean Twitter/X restricts access because scraping is too fast.

  • Use a scroll_pause_time of at least 5 seconds
  • Do not run more than one scraping process simultaneously
  • Add a pause of a few minutes between large sessions

Available Language Codes

Code Language
id Indonesian
en English
ja Japanese
es Spanish
fr French
ko Korean

Troubleshooting

❌ Error: WebDriver not found

Chrome is not detected or ChromeDriver does not match.

Solution:

  • Make sure Google Chrome is installed
  • The package will automatically download the appropriate ChromeDriver

❌ Error: Auth token invalid

The token you entered is invalid or expired.

Solution:

  1. Reopen x.com in your browser
  2. Log in again if necessary
  3. Retrieve the auth_token value again from the Developer Tools → Cookies tab
  4. Make sure there are no trailing spaces when copying and pasting

❌ Error: No tweets found

No tweets were found for the parameters you entered.

Solution:

  • Check your internet connection
  • Try more common/popular keywords
  • Check the date range — there might genuinely be no tweets in that period
  • Try lang=None (leaving language blank) — X's lang: filter often returns empty results on recent dates when combined with since:/until:
  • Ensure the auth_token is still valid

Browser does not appear

This is normal — the default mode is headless=True (without browser GUI).

If you want to see the scraping process visually:

scraper = TwitterScraper(auth_token=token, headless=False)

Requirements

  • Python 3.7+
  • Google Chrome (latest version)
  • Dependencies (automatically installed with the package):
    • pandas >= 2.0.0
    • selenium >= 4.0.0
    • webdriver-manager >= 4.0.0
    • requests >= 2.0.0

This tool was created for educational and scientific research purposes.

By using this tool, you agree to comply with:

The developer is not responsible for any misuse of this tool.


Contributing

Contributions are very welcome! How to contribute:

  1. Fork this repository
  2. Create a new branch: git checkout -b feature/new-feature
  3. Commit changes: git commit -m 'Add a new feature'
  4. Push to the branch: git push origin feature/new-feature
  5. Create a Pull Request

License

MIT License — see the LICENSE file for full details.


Support & Contact


Special Thanks To


Made with ❤️ for the data science & research community

⭐ If this project is helpful, give it a star on GitHub!

Metadata

Release files for panen-tweet 11.29.2026.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for panen-tweet 11.29.2026.1
File Size Uploaded Provenance Actions
panen_tweet-11.29.2026.1.tar.gz 31.7 kB With provenance Details for panen_tweet-11.29.2026.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for panen-tweet 11.29.2026.1
File Interpreter ABI Platform Actions
panen_tweet-11.29.2026.1-py3-none-any.whl Python 3 none any Details for panen_tweet-11.29.2026.1-py3-none-any.whl

Total release size: 51.6 kB

Release files / panen_tweet-11.29.2026.1.tar.gz

Download URL panen_tweet-11.29.2026.1.tar.gz
Size 31.7 kB
Tags Source
SHA-256 checksum
How to use checksums
f9927b66b728107cb0fb14c84052138a30c47847a9b8d3293bcbc4b9e64bbb27
BLAKE2b-256 checksum
How to use checksums
d7938df142211746fb2fc7c1c26af5bdd472e1d78f5db406c84f9531a9668fc5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / panen_tweet-11.29.2026.1-py3-none-any.whl

Download URL panen_tweet-11.29.2026.1-py3-none-any.whl
Size 19.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fb4375bd1e4d4a6ace32e4730e7c81a8e5f0c0f36fcbebae18b71f7bea38bef9
BLAKE2b-256 checksum
How to use checksums
8e26ddda0406270aab5525a0119840e3f383418d62d3b1fa892cda97111ef26f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for panen-tweet 11.29.2026.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for panen_tweet-11.29.2026.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page