---
title: "用 Python 抓取 Twitter（X）：推文、粉丝与 CSV 导出"
description: "Python 教程：用 TwexAPI REST API 抓取 X（Twitter）公开推文和粉丝，分页获取并保存为 CSV。不需要浏览器、代理或 X 账号。"
---

本指南用 Python 发送普通 HTTP 请求来抓取 X（Twitter）的公开数据：用高级搜索语法搜索推文、分页获取结果、导出粉丝列表，并全部保存为 CSV。不需要无头浏览器、代理或 X 账号，只需要一个 TwexAPI API Key。

## 准备

1. 在 [twexapi.io](https://twexapi.io/get-started) 注册账号，获得 20,000 免费 Credits，约可读取 4,000 条。
2. 在控制台复制 API Key 并设置为环境变量：

```bash
export TWEXAPI_KEY="twexapi_xxx"
pip install requests
```

## 搜索推文

[高级搜索接口](/zh/api-reference/search-endpoints/get-data-page-twitter-advanced-search-page-post)接收 `searchTerms`（搜索词列表）、`sortBy`（`Latest` 或 `Top`）和用于翻页的 `next_cursor`。每页最多返回 20 条推文。

```python
import os
import time

import requests

API = "https://api.twexapi.io"
HEADERS = {"Authorization": f"Bearer {os.environ['TWEXAPI_KEY']}"}


def paginate(path, body, max_items):
    """POST a cursor endpoint until max_items rows or the last page."""
    items, cursor = [], ""
    while len(items) < max_items:
        res = requests.post(f"{API}{path}", headers=HEADERS, json={**body, "next_cursor": cursor}, timeout=30)
        res.raise_for_status()
        page = res.json()
        items += [row for row in page.get("data", []) if row]
        cursor = page.get("next_cursor")
        if not page.get("has_next_page") or not cursor:
            break
        time.sleep(5)  # free Starter plan: 1 request per 5 seconds; paid plans allow 5+ per second
    return items[:max_items]


tweets = paginate(
    "/twitter/advanced_search/page",
    {"searchTerms": ["openai", "lang:en", "min_faves:100", "since:2026-10-01"], "sortBy": "Latest"},
    max_items=200,
)
print(len(tweets), "tweets")
```

`searchTerms` 支持与 X 搜索框相同的运算符：

| 运算符 | 示例 | 含义 |
| :--- | :--- | :--- |
| `from:` | `from:nasa` | 某个账号发的帖子 |
| `since:` / `until:` | `since:2026-10-01` | 日期范围 |
| `lang:` | `lang:zh` | 语言 |
| `min_faves:` | `min_faves:100` | 最少点赞数 |
| `-filter:replies` | | 排除回复 |

## 保存为 CSV

```python
import csv

with open("tweets.csv", "w", newline="", encoding="utf-8-sig") as f:
    writer = csv.writer(f)
    writer.writerow(["tweet_id", "created_at", "user", "likes", "retweets", "text"])
    for t in tweets:
        writer.writerow([
            t.get("tweet_id"),
            t.get("created_at"),
            (t.get("user") or {}).get("screen_name"),
            t.get("favorite_count"),
            t.get("retweet_count"),
            (t.get("text") or "").replace("\n", " "),
        ])
```

使用 `utf-8-sig` 编码，用 Excel 打开时中文和表情不会乱码。

## 抓取粉丝

[粉丝接口](/zh/api-reference/followers-following-endpoints/get-followers-cursor-apiendpoint-twitter-followers-page-post)使用同样的游标分页，`paginate` 函数可以直接复用。

```python
followers = paginate("/twitter/followers/page", {"screen_name": "nasa"}, max_items=1000)

with open("followers.csv", "w", newline="", encoding="utf-8-sig") as f:
    writer = csv.writer(f)
    writer.writerow(["username", "name", "followers", "location", "bio"])
    for u in followers:
        writer.writerow([u.get("username"), u.get("name"), u.get("followersCount"), u.get("location"), u.get("description")])
```

## 成本

典型读取每条 5 Credits，约每 1,000 条推文或粉丝 $0.05。上面的例子（200 条推文加 1,000 个粉丝）合计约 $0.06。准确单价见[价格说明](/zh/guides/pricing)。

## 为什么不用 Selenium、Playwright 或 twscrape？

X 在 2024 年初关闭了游客访问，浏览器类和开源爬虫现在需要已登录的 X 账号和轮换代理，而且 X 一改版就会失效。用 API 可以把这些维护工作交给服务方。更完整的对比见[自建 Twitter 爬虫 vs TwexAPI](/zh/comparison/scraper-vs-api)。

## 下一步

- [Twitter 抓取 API 概览](https://twexapi.io/twitter-scraper)：能抓取哪些数据，以及与 Apify 和官方 API 的对比。
- [错误处理](/zh/guides/error-handling)：遇到 `429` 和 `5xx` 时如何重试和退避。
- 只采集公开数据，并遵守隐私法规和 X 的条款。
