【问题标题】:Collecting tweets using screen names and saving them using Tweepy使用屏幕名称收集推文并使用 Tweepy 保存它们
【发布时间】:2016-04-22 09:38:04
【问题描述】:

我有一个 Twitter 网名列表,并且想为每个网名收集 3200 条推文。以下是我改编自https://gist.github.com/yanofsky/5436496的代码

#initialize a list to hold all the tweepy Tweets
alltweets = []

#screen names
r=['user_a', 'user_b', 'user_c']

#saving tweets
writefile=open("tweets.csv", "wb")
w=csv.writer(writefile)

for i in r:

    #make initial request for most recent tweets (200 is the maximum allowed count)
    new_tweets = api.user_timeline(screen_name = i, count=200)

    #save most recent tweets
    alltweets.extend(new_tweets)

    #save the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1

    #keep grabbing tweets until there are no tweets left to grab
    while len(new_tweets) > 0:
        print "getting tweets before %s" % (oldest)

        #all subsiquent requests use the max_id param to prevent duplicates
        new_tweets = api.user_timeline(screen_name = i[0],count=200,max_id=oldest)

        #save most recent tweets
        alltweets.extend(new_tweets)

        #update the id of the oldest tweet less one
        oldest = alltweets[-1].id - 1

        print "...%s tweets downloaded so far" % (len(alltweets))

    #write the csv
    for tweet in alltweets:
        w.writerow([i, tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")])

writefile.close()

最后,最终的 csv 文件包含 user_a 的 3200 条推文,user_b 的大约 6400 条推文和 user_c 的 9600 条推文。上述代码中有些地方不正确。每个用户应该有大约 3200 条推文。谁能指出我的代码有什么问题?谢谢。

【问题讨论】:

    标签: python tweepy


    【解决方案1】:

    因为您使用.extend() 添加到alltweets,所以for 循环的每次迭代都会导致下一个用户的所有推文都添加到前一个推文中。所以你想在每个for循环迭代开始时清除alltweets

    for i in r:
        alltweets = []
        ...
    

    【讨论】:

    • 谢谢,但这只会保存最后一个人 (user_c) 的推文。问题依然存在。
    • 还有其他建议吗?
    • 哦,哈哈。它正在编写来自所有 3 个用户的推文,它只是从 user_c 报告它,因为那是我们 for 循环结束时 i 的值。我将更改我的答案,以便对您的代码进行更少的更改。
    猜你喜欢
    • 1970-01-01
    • 2018-06-29
    • 2019-10-03
    • 2015-06-17
    • 2016-06-29
    • 2018-04-19
    • 2019-02-16
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多