Search code examples
pythontwittertweepy

AttributeError: using Tweepy and Twitter API


I am trying to extract information from Twitter's API using Tweepy. 90% of the code works fine, but when I try to get the followers_count from each tweet, I run into an error.

The code I am using is:

# Running only on handle returns a dataframe 
tweets = api.user_timeline(user_id=user_id, count=number_tweets, tweet_mode="extended")
print("Number of tweets extracted: {}.\n".format(len(tweets)))
data = pd.DataFrame(data=[tweet.full_text for tweet in tweets], columns= ["Text"])
data["Tweet length"] = np.array([len(tweet.full_text) for tweet in tweets])
data["Tweet ID"] = np.array([tweet.id for tweet in tweets])
data["Tweet Date"] = np.array([tweet.created_at for tweet in tweets])
data["Tweet source"] = np.array([tweet.source for tweet in tweets])
data["Tweet likes"] = np.array([tweet.favorite_count for tweet in tweets])
data["Tweet retweets"] = np.array([tweet.retweet_count for tweet in tweets])
# Line to be added here #
data = data.sort_values(by="Tweet Date", ascending = False)

When I got to add in the following line:

data["User followers"] = np.array([tweet.followers_count for tweet in tweets])

The error message is:

AttributeError: 'Status' object has no attribute 'followers_count'


Solution

  • Your code in the first snippet refers to the Tweet Object, i.e. they all refer to an instance of a Tweet that you will be able to get the values from using the Attributes. You can see this by the name of the attributes.

    On the second snippet

    data["User followers"] = np.array([tweet.followers_count for tweet in tweets])

    This is not a Tweet object but instead a User Object. Therefore the dictionary that you refer to (tweets) will not have attributes with the name of followers_count. You can see from the documentation here that Tweet object does not contain any followers_count attribute.

    In order to solve this, you need to make a request to get the User Object. You can see the documentation for that here - User object