简体   繁体   中英

How to get original favorite count, and each user's follower count, from Twitter streaming API in Python

I'm attempting to extract individual pieces of data from the public stream of tweets for two tracked keywords, using the Python package TwitterAPI .

I would ideally like to get the original favorite count for the retweeted_status object (not for the user's status wrapper) but am having difficulty doing so, since both print(retweeted_status['favorite_count']) and print(status['favorite_count']) always return zero.

Failing that, I would like to be able to get the follower count of each user in the stream. I can see an entity called 'friends_count' in the full json returned from each tweet when I run print(item) , but if I run print(user['friends_count']) I get the following error:

  Traceback (most recent call last):
  File "twitter.py", line 145, in <module>
    friends()
  File "twitter.py", line 110, in favourites
    print(user['friends_count'])
KeyError: 'friends_count'

This is what my full code looks like at the moment:

import sys

sys.path.append('/Library/Python/2.6/site-packages')

from TwitterAPI import TwitterAPI

import string


OAUTH_SECRET    = "foo"

OAUTH_TOKEN     = "foo"

CONSUMER_KEY    = "foo"

CONSUMER_SECRET = "foo"

def friends():

  TRACK_TERM = 'hello'

  api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET)

  f = api.request('statuses/filter', {'track': TRACK_TERM})

  for user in f:
    print(user['friends_count'])


def favorite():

  TRACK_TERM = 'kanye'

  api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET)

  h = api.request('statuses/filter', {'track': TRACK_TERM})

  for retweeted_item in h:
    print(retweeted_item['favorite_count'])

if __name__ == '__main__':

    try:

        friends()

        favorite()

    except KeyboardInterrupt:

        print '\nGoodbye!'

Any advice or information would be much appreciated - I assume I have made a mistake somewhere in my syntax (I am a Python beginner!) which is throwing KeyErrors but haven't been able to work out what it is from either the documentation for the TwitterAPI package, nor the Twitter API itself after hours of searching.

EDIT: this is what the streaming API returns for a single user's post when I run for user in f print(user) (I don't know how to make it more readable/wrap the text on Stack Overflow, sorry) - you can see both 'friends_count' and 'followers_count' return a number but I don't know how to print them out individually without it just resulting in a KeyError.

{u'contributors': None, u'truncated': False, u'text': u'Hearing Kanye spit on a Drake beat is just really a lot for me!!!! I was not prepared!!', u'is_quote_status': False, u'in_reply_to_status_id': None, u'id': 719940912453853184, u'favorite_count': 0, u'source': u'<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>', u'retweeted': False, u'coordinates': None, u'timestamp_ms': u'1460482264041', u'entities': {u'user_mentions': [], u'symbols': [], u'hashtags': [], u'urls': []}, u'in_reply_to_screen_name': None, u'id_str': u'719940912453853184', u'retweet_count': 0, u'in_reply_to_user_id': None, u'favorited': False, u'user': {u'follow_request_sent': None, u'profile_use_background_image': True, u'default_profile_image': False, u'id': 247986350, u'verified': False, u'profile_image_url_https': u'https://pbs.twimg.com/profile_images/715358123108601856/KM-OCY2D_normal.jpg', u'profile_sidebar_fill_color': u'DDEEF6', u'profile_text_color': u'333333', u'followers_count': 277, u'profile_sidebar_border_color': u'FFFFFF', u'id_str': u'247986350', u'profile_background_color': u'C0DEED', u'listed_count': 1, u'profile_background_image_url_https': u'https://pbs.twimg.com/profile_background_images/695740599/089d0a4e4385f2ac9cad05498169e606.jpeg', u'utc_offset': -25200, u'statuses_count': 6024, u'description': u'this is my part, nobody else speak', u'friends_count': 298, u'location': u'las vegas', u'profile_link_color': u'FFCC4D', u'profile_image_url': u'http://pbs.twimg.com/profile_images/715358123108601856/KM-OCY2D_normal.jpg', u'following': None, u'geo_enabled': True, u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/247986350/1454553801', u'profile_background_image_url': u'http://pbs.twimg.com/profile_background_images/695740599/089d0a4e4385f2ac9cad05498169e606.jpeg', u'name': u'princess laser tag', u'lang': u'en', u'profile_background_tile': True, u'favourites_count': 9925, u'screen_name': u'hannahinloafers', u'notifications': None, u'url': u'http://eecummingsandgoings.tumblr.com', u'created_at': u'Sun Feb 06 00:49:24 +0000 2011', u'contributors_enabled': False, u'time_zone': u'Pacific Time (US & Canada)', u'protected': False, u'default_profile': False, u'is_translator': False}, u'geo': None, u'in_reply_to_user_id_str': None, u'lang': u'en', u'created_at': u'Tue Apr 12 17:31:04 +0000 2016', u'filter_level': u'low', u'in_reply_to_status_id_str': None, u'place': None}

I've solved it, and think it was an issue with me not understanding how to retrieve JSON from nested dictionaries. This worked:

if 'retweeted_status' in item:

    item2 = item['retweeted_status']
    print(item2['favorite_count'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM