如何使用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
相关产品推荐
相关产品推荐

