获取与推文相对应的各种数据

时间:2016-02-26 17:44:02

标签: python-2.7 twitter tweepy

我正在尝试从twitter获取数据进行处理。请查看代码我想要与对应于给定主题的特定推文相对应的各种数据。我能够获取数据(created_at,text,username,user_id)。我尝试提取时会显示错误(location,followers_count,friends_count,retweet_count)。

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import time
import json

ckey = '***********************'
csecret = '************************'
atoken ='*************************'
asecret = '**********************'

class listener(StreamListener):

  def on_data(self,data):
    try:
         all_data = json.loads(data)

         tweet = all_data["text"]

         username = all_data["user"]["screen_name"]

         timestamp = all_data["created_at"]

         user_id = all_data["id_str"]

         location = all_data["location"]

         followers_count = all_data["followers_count"]

         friends_count = all_data["friends_count"]

         retweet_count = all_data["retweet_count"]

         saveThis = str(time.time())+'::'+timestamp+'::'+username+'::'+user_id+'::'+tweet+'::'+followers_count+'::'+friends_count+'::'+retweet_count+'::'+location
         saveFile = open('clean2.txt','a')
         saveFile.write(saveThis)
         saveFile.write('\n')
         saveFile.close
         return True
     except BaseException, e:
         print 'failed on data,',str(e)
         time.sleep(5)

 def on_error(self, status):
     print status

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["tweepy"])#topic

1 个答案:

答案 0 :(得分:0)

all_data["location"]失败的原因是推文没有这样的属性:https://dev.twitter.com/overview/api/tweets

  • 与friends_count,followers_count相同 - 它们是用户的属性,而不是推文。

代码不应该在all_date["retweet_count"]失败,因为推文具有这样的属性。

P.S。报告错误时请包含错误消息(即使您跳过完整的错误引用)。让你更容易帮助你,否则你必须猜出错误可能是什么。

相关问题