Irma
Irma

Reputation: 11

Using TwitterAPI (python) to search tweets from specific users

For my research I would like to generate an overview of tweets posted by specific users (both recent and historical - through premium search). I have no experience with coding, so started with some very basic videos explaining the possibilites. As I would like to search the historical archive of twitter, I concluded tweepy would not be the best option, and have been following a tutorial to use TwitterAPI instead. I ended up with the following:

SEARCH_TERM = 'example'
COUNT = 100

r = api.request('search/tweets', {'q': SEARCH_TERM, 'count': COUNT})

a = 1
for item in r.get_iterator():
    print(a)
    print(item['text'] if 'text' in item else item)
    a=a+1
print('\nQUOTA: %s' % r.get_quota())

However, I cannot seem to work out how I can search for one specific username, instead of a generic search term. I tried to just add the username (twitterhandle) as a search term, both with and without the @, but this does not give me the tweets for that specific account.

Does anyone has experience with this?

Upvotes: 1

Views: 1096

Answers (1)

Jonas
Jonas

Reputation: 4048

You will need to use the statuses/user_timeline request. Simply, make the following change to your example code:

r = api.request('statuses/user_timeline', 
                {'screen_name':SEARCH_TERM, 'count':COUNT})

Set SEARCH_TERM to the user handle. You can also up COUNT to 200.

You should be aware that neither statuses/user_timeline nor search/tweets are Premium Search requests. To make a Premium Search request you would need authorization from Twitter, and then you would make this change to your example:

r = api.request('tweets/search/%s/:%s' % (PRODUCT, LABEL), 
                {'query':'from:'+SEARCH_TERM, 'maxResults':500})

For either type of request it is also possible to get many more results than the stated maximum count. For this you will need to use Twitter's method for getting successive pages of results. TwitterAPI has a helper class that does this for you. A short example can be found here and can be modified to use the Premium Search request or the user timeline request.

Upvotes: 1

Related Questions