You need to enable JavaScript to run this app. 如何使用Snscrape遍历Twitter用户列表批量抓取推文?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Snscrape遍历Twitter用户列表批量抓取推文?

错误原因

报错AttributeError: 'generator' object has no attribute 'format'的核心原因是format方法的调用位置错误:format是字符串对象的方法,你错误地将它挂载到了get_items()返回的生成器对象后,同时原代码缺少对用户列表的外层遍历逻辑,没有逐个取出列表里的用户名参数传入搜索条件。

修复后的可运行代码

import snscrape.modules.twitter as sntwitter
tweets_list1 = []
users_name = [{'username':'@bbcmundo'},{'username':'@nytimes'}]

# 外层遍历所有待抓取的用户
for user in users_name:
    current_username = user['username']
    # 先对搜索参数字符串做格式化,传入当前遍历到的用户名
    search_rule = 'from:{}'.format(current_username)
    # 抓取当前用户的推文,每个用户最多返回100条
    for i,tweet in enumerate(sntwitter.TwitterSearchScraper(search_rule).get_items()):
        if i>100:
            break
        tweets_list1.append([
            tweet.date, tweet.id, tweet.content, tweet.url,
            tweet.user.username, tweet.user.followersCount,tweet.replyCount,
            tweet.retweetCount, tweet.likeCount, tweet.quoteCount, tweet.lang,
            tweet.outlinks, tweet.media, tweet.retweetedTweet, tweet.quotedTweet,
            tweet.inReplyToTweetId, tweet.inReplyToUser, tweet.mentionedUsers,
            tweet.coordinates, tweet.place, tweet.hashtags, tweet.cashtags
        ])

如果需要调整单用户抓取的推文上限,直接修改if i>100中的数值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 16:39:02