【问题标题】:Return and save 800 friend's tweets using Tweepy使用 Tweepy 返回并保存 800 条朋友的推文
【发布时间】:2019-06-21 02:03:51
【问题描述】:

我正在尝试使用 api.home_timeline 提取我朋友的推文。我不想流式传输它,但我想将 800 条推文、屏幕名称和他们的喜欢/收藏计数保存到 csv 文件中。 Twitter 一次只允许 200 条推文。鉴于我已经指定了我的密钥,这就是我目前所拥有的:

 def data_set(handle):
    auth=tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
    auth=set_access_token(ACCESS_KEY,ACCESS_SECRET)
    api=tweepy.API(auth)
    count_tweets=api.home_timeline(screen_name=handle,count=200)
    twits=[]
    tweet_data=[tweet.text for tweet in count_tweets]

    for t in count_tweets:
       twits.append(t)

if __name__== '__main__':
tweet_data('my twitter name')

我最初的计划是拥有多个 count_tweets,例如 count_tweet1 等。我不确定如何进行其余的。非常感谢任何建议。

【问题讨论】:

    标签: python api twitter tweepy


    【解决方案1】:

    Twitter 关注pagination。对于每个请求,您最多可以提供 200 条推文(在 home_timeline 的情况下)。您获得的 200 条推文是基于受欢迎程度的。您可以通过遍历页面从用户的时间轴中获取所有推文。 Tweepy 提供 Cursor 功能来遍历页面

    为您的案例编辑了代码:

    def data_set(handle):
        auth=tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
        auth=set_access_token(ACCESS_KEY,ACCESS_SECRET)
        api=tweepy.API(auth)
        tweet_data = []
        for page in tweepy.Cursor(api.user_timeline, screen_name=handle, count=200, tweet_mode='extended').pages():
            for tweet in page:
                tweet_data.append(tweet.full_text)
        return tweet_data
    
    ## Not sure why the following lines are needed
    #    twits=[]
    #    tweet_data=[tweet.text for tweet in count_tweets]
    
    #    for t in count_tweets:
    #        twits.append(t)
    
    if __name__== '__main__':
        print(data_set('my twitter name'))
    

    我在代码中使用了api.user_timeline 而不是api.home_timeline,因为您说您正试图从您朋友的时间线中获取推文。如果api.home_timeline 满足您的用例,您可以替换它。

    【讨论】:

      猜你喜欢
      • 2014-12-06
      • 2016-09-20
      • 2018-10-20
      • 1970-01-01
      • 2015-06-17
      • 2014-10-24
      • 2015-09-07
      • 1970-01-01
      • 2015-12-19
      相关资源
      最近更新 更多