You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无Twitter API时使用twscrape爬取推特数据并导出CSV的技术求助

解决twscrape登录后停止运行并导出推文到CSV的问题

修改后的完整代码

import asyncio
import pandas as pd
from twscrape import API, gather
from twscrape.logger import set_log_level

# 设置日志级别,方便查看登录和请求状态
set_log_level("INFO")

async def main():
    api = API()  # 默认使用accounts.db存储账号信息

    # 添加账号(已存在的账号会自动跳过重复添加)
    await api.pool.add_account("pevers123", "2051Lb57", "peter.evers123@hotmail.com", "2051Lb57")
    await api.pool.add_account("maxevers123", "2051Lb57", "max.evers123@hotmail.com", "2051Lb57")
    
    # 批量登录并反馈结果
    login_results = await api.pool.login_all()
    for acc, success in login_results.items():
        print(f"账号 {acc.user} 登录 {'成功' if success else '失败'}")

    # 统一搜索参数,避免重复请求
    search_query = "easyjet eco-friendly environment"
    tweet_limit = 20  # 可按需调整获取的推文数量

    # 收集不同标签下的推文
    latest_tweets = await gather(api.search(search_query, limit=tweet_limit))
    top_tweets = await gather(api.search(search_query, limit=tweet_limit, kv={"product": "Top"}))

    # 合并推文并去重(通过推文ID确保唯一性)
    all_tweets = latest_tweets + top_tweets
    unique_tweets = list({t.id: t for t in all_tweets}.values())

    # 提取需要的字段:推文内容、格式化后的发布日期
    tweet_data = []
    for tweet in unique_tweets:
        tweet_data.append({
            "推文内容": tweet.rawContent,
            "发布日期": tweet.date.strftime("%Y-%m-%d %H:%M:%S")  # 生成R易读取的日期格式
        })

    # 导出为CSV文件
    df = pd.DataFrame(tweet_data)
    df.to_csv("easyjet_可持续推文.csv", index=False, encoding="utf-8-sig")
    print(f"成功导出 {len(df)} 条推文到CSV文件")

if __name__ == "__main__":
    asyncio.run(main())

原代码的问题分析

  • 重复搜索未留存结果:原代码两次调用gather(api.search(...))但未保存返回的推文数据,后续async for循环因请求资源被占用或搜索上下文结束,导致无输出。
  • 缺失CSV导出逻辑:没有将提取的推文内容和日期写入文件的代码,无法生成可用的CSV。
  • 无错误反馈机制:登录、搜索过程中出现问题时没有明确提示,难以定位故障点。

操作步骤

  1. 安装依赖库:打开终端执行以下命令:
    pip install twscrape pandas
    
  2. 验证账号信息:确保代码中的账号、密码、邮箱为有效的X(Twitter)账号(注意:twscrape不支持开启双重认证的账号)。
  3. 运行脚本:执行Python代码,完成后当前目录会生成easyjet_可持续推文.csv,直接导入R即可使用。
  4. 按需调整参数:修改tweet_limit可调整获取的推文数量,注释top_tweets相关代码可只获取Latest标签的推文。

注意事项

  • 若登录失败,检查账号是否被X限制,或是否开启了双重认证。
  • 使用utf-8-sig编码确保R读取CSV时不会出现乱码。
  • 避免短时间内发起大量请求,防止账号被临时限制。

内容的提问来源于stack exchange,提问作者Floris Evers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:18:19