Search code examples
pythontweepy

How to get individual items from tweepy stream


I can't seem to get individual items i.e. getting just the text or just the user.

I've tried to use it as a dictionary or list but nothing seems to work. I don't, however, know how trustworthy my testing is as I'm an amateur.

def on_data(self, data):
        try:
            print(data.text(?))
            with open(self.fetched_tweets_filename, 'a') as tf:
                tf.write(data)
            return True
        except BaseException as e:
            print("Error on_data %s" % str(e))
        return True

I want "Sample tweet" however I'm getting various can't be parsed errors


Solution

  • The on_data method of StreamListener receives raw data as a string.
    You can use json.loads to deserialize the JSON to a dictionary to access the "text" key.
    See https://github.com/tweepy/tweepy/blob/29bae1fde3ae0636fa13e5ed69f68f2af75c110b/tweepy/streaming.py#L42-L48.

    Alternatively, you can use on_status instead to obtain a Status object, which has the text attribute.