惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Securelist
有赞技术团队
有赞技术团队
WordPress大学
WordPress大学
V
V2EX
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
The Register - Security
The Register - Security
Recorded Future
Recorded Future
Y
Y Combinator Blog
小众软件
小众软件
Jina AI
Jina AI
V2EX - 技术
V2EX - 技术
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
宝玉的分享
宝玉的分享
The Hacker News
The Hacker News
C
Cybersecurity and Infrastructure Security Agency CISA
K
Kaspersky official blog
博客园 - 三生石上(FineUI控件)
T
Threatpost
博客园 - 聂微东
Scott Helme
Scott Helme
IT之家
IT之家
N
Netflix TechBlog - Medium
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
MongoDB | Blog
MongoDB | Blog
T
Tor Project blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
A
About on SuperTechFans
酷 壳 – CoolShell
酷 壳 – CoolShell
C
CERT Recently Published Vulnerability Notes
P
Palo Alto Networks Blog
Spread Privacy
Spread Privacy
C
Check Point Blog
L
LINUX DO - 最新话题
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Last Week in AI
Last Week in AI
Attack and Defense Labs
Attack and Defense Labs
T
Tailwind CSS Blog
罗磊的独立博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Webroot Blog
Webroot Blog
Help Net Security
Help Net Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
爱范儿
爱范儿
PCI Perspectives
PCI Perspectives
Security Latest
Security Latest

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Scrape Twitter/X Data: Complete Guide for 2026
AlterLab · 2026-04-24 · via DEV Community

Disclaimer: This guide covers extracting publicly accessible data. Always review a site's robots.txt and Terms of Service before scraping.

Extracting data from Twitter/X requires moving beyond standard HTTP requests. The platform is a heavy Single Page Application (SPA) built on React, utilizing complex client-side rendering, dynamic data fetching via GraphQL, and strict rate limiting.

This guide demonstrates how to build a robust pipeline for extracting public tweets, profile metadata, and trending topics using Python, handling the technical requirements of modern web scraping.

Why collect social data from Twitter/X?

Engineering and data teams typically extract public X data for three primary workflows:

  1. Market research and sentiment analysis: Aggregating public mentions of brand names, product launches, or competitors to feed natural language processing pipelines.
  2. Real-time event monitoring: Tracking public announcements, service outages, or breaking news events via verified accounts.
  3. Financial data modeling: Correlating public executive statements or official corporate announcements with market movements.

To power these use cases, you need structured, reliable data extraction.

Technical challenges

Attempting to run a standard curl or Python requests.get() against a Twitter/X URL will fail to return the actual content. The server responds with a minimal HTML shell containing JavaScript bundles. The actual data (tweets, profiles) is fetched asynchronously and rendered in the browser.

To access public content, your scraping infrastructure must handle:

  • JavaScript Execution: You need a headless browser (like Chromium) to execute the React application and wait for the DOM to hydrate.
  • Dynamic Loading: Content loads infinitely as the user scrolls. Extracting a full timeline requires simulating user interaction.
  • Rate Limiting: Aggressive request patterns from a single IP address will result in rate limits or block pages.

Managing headless browser clusters and proxy pools at scale introduces significant infrastructure overhead. This is where an Anti-bot bypass API becomes necessary to abstract the browser management and focus on data extraction.

Quick start with AlterLab API

To bypass the infrastructure setup, we will use AlterLab to handle the JavaScript rendering and proxy rotation automatically.

First, ensure you have reviewed the Getting started guide to configure your environment.

Here is how to extract the rendered HTML of a public profile using Python.

```python title="scrape_twitter_profile.py" {4-6}

ALTERLAB_API_KEY = "your_api_key_here"
TARGET_URL = "https://twitter.com/XDevelopers"
ENDPOINT = "https://api.alterlab.io/v1/scrape"

payload = {
"url": TARGET_URL,
"render_js": True,
"wait_for_selector": '[data-testid="primaryColumn"]'
}

headers = {
"X-API-Key": ALTERLAB_API_KEY,
"Content-Type": "application/json"
}

response = requests.post(ENDPOINT, json=payload, headers=headers)
print(response.json().get("content"))




For environments where you prefer shell scripting or testing via the command line, the equivalent request looks like this:



```bash title="Terminal" {3-5}
curl -X POST https://api.alterlab.io/v1/scrape \
  -H "X-API-Key: your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://twitter.com/XDevelopers",
    "render_js": true,
    "wait_for_selector": "[data-testid=\"primaryColumn\"]"
  }'

Enter fullscreen mode Exit fullscreen mode

By setting render_js to true and providing a wait_for_selector, we instruct the API to hold the connection open until the React application has fully loaded the main content column.

Extracting structured data

Once you have the fully rendered HTML, the next step is parsing it into structured formats like JSON. Twitter/X uses heavily obfuscated CSS class names that change frequently (e.g., css-1dbjc4n). Relying on these classes leads to brittle scrapers.

Instead, rely on data-testid attributes, which X developers use for their own internal testing. These attributes are significantly more stable.

Here is a Python example using BeautifulSoup to parse the rendered HTML and extract public tweets.

```python title="parse_tweets.py" {11-15}
from bs4 import BeautifulSoup

def extract_tweets(html_content):
soup = BeautifulSoup(html_content, 'html.parser')
tweets_data = []

# Locate all tweet articles
articles = soup.find_all('article', attrs={'data-testid': 'tweet'})

for article in articles:
    # Extract text content
    text_element = article.find('div', attrs={'data-testid': 'tweetText'})
    tweet_text = text_element.get_text(separator=' ', strip=True) if text_element else None

    # Extract timestamp
    time_element = article.find('time')
    timestamp = time_element['datetime'] if time_element and time_element.has_attr('datetime') else None

    if tweet_text:
        tweets_data.append({
            "text": tweet_text,
            "timestamp": timestamp
        })

return json.dumps(tweets_data, indent=2)

Enter fullscreen mode Exit fullscreen mode

Assume html_content is the response from the previous step

print(extract_tweets(html_content))




<div data-infographic="steps">
  <div data-step data-number="1" data-title="Request" data-description="Send URL to API with JS rendering enabled"></div>
  <div data-step data-number="2" data-title="Wait" data-description="Block until data-testid='tweet' appears in DOM"></div>
  <div data-step data-number="3" data-title="Parse" data-description="Extract structured text and timestamps via BeautifulSoup"></div>
</div>

## Best practices

When building pipelines for social platforms, adherence to best practices ensures your scraper remains reliable and compliant.

1.  **Respect Robots.txt**: Always check `https://twitter.com/robots.txt`. Certain paths are explicitly disallowed. Ensure your scraper only targets paths meant for public visibility and indexing.
2.  **Handle Dynamic Content gracefully**: Elements load asynchronously. Never hardcode static sleep times (e.g., `time.sleep(5)`). Always use explicit waits for specific DOM elements, as shown with the `wait_for_selector` parameter.
3.  **Implement Rate Limiting**: Even when scraping public data, aggressive polling strains target servers. Implement exponential backoff and jitter in your retry logic to simulate organic traffic patterns.

<div data-infographic="try-it" data-url="https://twitter.com/XDevelopers" data-description="Test JavaScript rendering on a public X profile"></div>

## Scaling up

Transitioning from a local script to a production data pipeline requires handling high concurrency and managing costs.

If you are tracking hundreds of public profiles, serial execution is too slow. You must implement asynchronous request batching. Python's `asyncio` combined with `aiohttp` allows you to dispatch multiple requests concurrently while waiting for the browser rendering to complete on the server side.

When operating at this scale, monitor your infrastructure expenses. Refer to the [AlterLab pricing](/pricing) page to model costs based on your expected monthly request volume and JavaScript rendering requirements. Using a managed service often yields a lower total cost of ownership compared to maintaining a fleet of EC2 instances running Puppeteer and managing your own proxy rotations.

## Key takeaways

Extracting data from modern SPAs requires specific tooling. Raw HTTP clients are insufficient for React-heavy applications. By utilizing headless browsers, targeting stable `data-testid` attributes, and relying on managed infrastructure to handle the rendering overhead, you can build reliable pipelines for public social data. Always prioritize compliant access and respect the target platform's operational limits.

### Related guides
*   [How to Scrape Instagram](/blog/how-to-scrape-instagram-com)
*   [How to Scrape YouTube](/blog/how-to-scrape-youtube-com)
*   [How to Scrape Reddit](/blog/how-to-scrape-reddit-com)

Enter fullscreen mode Exit fullscreen mode