【问题标题】:collecting tweets using tweepy cursor使用 tweepy 光标收集推文
【发布时间】:2019-10-03 00:10:41
【问题描述】:

我想将包含一些关键词的推文(python 字典格式)收集到一个 csv 文件中。我使用了 tweepy 光标。但它什么也没返回。

按照“Managing Tweepy API Search”中的答案,我尝试使用光标收集推文。但是代码在几秒钟后停止,没有返回任何消息。

import TwitterCredentials
import tweepy
import csv
from tweepy import OAuthHandler
import json

def authenticate():
    auth=OAuthHandler(TwitterCredentials.consumerKey, 
    TwitterCredentials.consumerSecretKey)
    auth.set_access_token(TwitterCredentials.accessToken,
    TwitterCredentials.accessTokenSecret)
    api=tweepy.API(auth)

    return api

def collectTweet(api, query, max_tweets):
    i=1
    for tweet in tweepy.Cursor(api.search, q=query).items(max_tweets):
        loadCsvFile(json.loads(tweet))
        print(str(i)+ " ")
        i+=1


def loadCsvFile(tweet): 
    csv_file.writerow([tweet['id'],tweet['created_at'],tweet['text'],
    tweet['retweet_count'],tweet['source']])



if __name__ == '__main__':

    query=['air pollution', 'PM 2.5']
    max_tweets=500

    f=open('collected_tweets.csv', 'w')
    csv_file=csv.writer(f)
    csv_file.writerow(['id','created_at','text',
    'retweet_count','source'])

    api=authenticate()
    collectTweet(api, query, max_tweets)

我想获取字典格式的消息,以便从中提取 id、created_at、text、源信息。

此代码没有返回任何错误,也没有返回任何消息。

【问题讨论】:

    标签: file csv tweets


    【解决方案1】:

    tweepy.cursor 返回状态,其中 _json 是所有推文字段都存在的字典。所以代码应该是

    for status in tweepy.Cursor(api.search, q=query, lang='en').items(max_tweets):
               loadCsvFile(status._json)
    

    ... 然后就成功了。

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 1970-01-01
      • 2017-04-12
      • 2016-06-29
      • 2019-06-02
      • 2021-12-27
      • 2014-01-18
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多