首页 > 解决方案 > Python:如何使用 Snscrap 遍历 Twitter 用户列表?

问题描述

我试图通过用户列表检索推文,但是在 snscrape 函数中,此参数在引号内,这使得用户名被视为固定输入

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

for i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:{}').get_items().format(username)):
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])

作为输出Python得到:

`AttributeError: 'generator' object has no attribute 'format'

此代码可以很好地用用户名替换花括号并删除 .format 属性。如果要复制此代码,请确保使用以下命令安装 snscrape 库:

pip install git+https://github.com/JustAnotherArchivist/snscrape.git

我真的很感激你能给我的任何指导。

标签: pythontwitterscrapyweb-scraping-language

解决方案


我发现了一些我在编写这段代码时所犯的错误。因此,我想与大家分享,以防万一您需要它并克服您遇到同样或类似问题的困扰:

首先:我将 users_name 格式从字典更改为列表项。

第二:我把格式属性放在了正确的位置。紧接着文字输入功能

第三:我添加了一个嵌套循环来抓取每个 Twitter 用户帐户

users_name = ['bbcmundo','nytimes']
for n, k in enumerate(users_name):
    for i,tweet in enumerate(sntwitter.TwitterSearchScraper('from:{}'.format(users_name[n])).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])

我希望它会有所帮助


推荐阅读