'str' object has no attribute 'user'

Question:

I am trying to get some tweets using Tweepy library, but I am receiving this error

AttributeError: 'str' object has no attribute 'user'

I used this same code some months back and I didn’t encounter this error, I don’t know why I am receiving this.

Here is the code:

def tweets_mining(csv_file, search_query, num_tweets):
    with open(csv_file, 'w', encoding='utf8', newline='') as file:
        thewriter = writer(file)
        header = ['tweet_id', 'time_created', 'tweet', 'location', 'retweets', 'likes']
        thewriter.writerow(header)

        for tweet in tweepy.Cursor(api.search_tweets,
                                   q=search_query,
                                   tweet_mode="extended",
                                   result_type="recent",
                                   lang="en").items(num_tweets):
            tweet_id = tweet.id
            time_created = tweet.created_at
            tweet = tweet.full_text
            location = tweet.user.location
            retweets = tweet.retweet_count
            likes = tweet.favorite_count
            row = [tweet_id, time_created, tweet, location, retweets, likes]
            thewriter.writerow(row)

search_term = "first search"

search_query = search_term + " -filter:links AND -filter:retweets AND -filter:replies"

tweets_mining('first_search.csv', search_query, 10)

This is the error message:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~AppDataLocalTemp/ipykernel_7884/2036184101.py in <module>
      3 search_query = search_term + " -filter:links AND -filter:retweets AND -filter:replies"
      4 
----> 5 tweets_mining('first_search.csv', search_query, 10)

~AppDataLocalTemp/ipykernel_7884/1256763917.py in tweets_mining(csv_file, search_query, num_tweets)
     13             time_created = tweet.created_at
     14             tweet = tweet.full_text
---> 15             location = tweet.user.location
     16             retweets = tweet.retweet_count
     17             likes = tweet.favorite_count

AttributeError: 'str' object has no attribute 'user'

Answers:

please pay attention to the line tweet = tweet.full_text. This line is overriding your tweet variable to string. Try using different variable name.

Answered By: Shashi Kant
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.