scrapy Python:如何使用Snscrape遍历Twitter用户列表?

k97glaaz  于 2022-11-09  发布在  Python
关注(0)|答案(2)|浏览(520)

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

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属性。如果你想复制这段代码,请确保使用以下代码安装snscrap库:

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

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

wvyml7n5

wvyml7n51#

我在写这段代码的时候发现了一些错误。所以,我想和大家分享一下,以防万一你们需要它,并克服你们遇到的同样的问题或类似的问题:
首先:我修改了users_name的格式,从一个字典改为一个列表项。
第二:我把format属性放在了正确的位置。就在文本输入函数之后
第三:我添加了一个嵌套循环来抓取每个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])

我希望能有所帮助

xe55xuns

xe55xuns2#

通过使用多个条件,可以避免发出多个请求:

users = ['bbcmundo','nytimes']
filters = ['since:2022-07-06', 'until:2022-07-07']
from_filters = []
for user in users:
    from_filters.append(f'from:{user}')
filters.append(' OR '.join(from_filters))
tweets = list(sntwitter.TwitterSearchScraper(' '.join(filters)).get_items())

# The argument is 'since:2022-07-06 until:2022-07-07 from:bbcmundo OR from:nytimes'

相关问题