Python: How to search tweets and store in database?
<p>I've got a nice Python script that currently prints out the past 200 tweets from a given username. </p>

<p>However, I'd like to modify it so that instead it will collect the past 200 tweets that include a certain hashtag (from any username) and then I'd like to store those results in a database.</p>

<p>Can anyone provide a suggestion on how to modify the code below?</p>

<pre><code>import sys
import operator
import requests
import json
import twitter

twitter_consumer_key = 'XXXX'
twitter_consumer_secret = 'XXXX'
twitter_access_token = 'XXXX'
twitter_access_secret = 'XXXX'

twitter_api = twitter.Api(consumer_key=twitter_consumer_key, consumer_secret=twitter_consumer_secret, access_token_key=twitter_access_token, access_token_secret=twitter_access_secret)

statuses = twitter_api.GetUserTimeline(screen_name=handle, count=200, include_rts=False)

for status in statuses:
  if (status.lang == 'en'):
    print status
</code></pre>

<p>Not familiar with the twitter package but this could be a suggestion that you can work on. Depends on how you want to save the tweet, you can replace the "print status" with the way you want. <strong>However, this only allows you to filter the 200 tweets rather than get the 200 tweets that contain certain hashtag.</strong></p>

<pre><code>import sys
import operator
import requests
import json
import twitter

twitter_consumer_key = 'XXXX'
twitter_consumer_secret = 'XXXX'
twitter_access_token = 'XXXX'
twitter_access_secret = 'XXXX'

twitter_api = twitter.Api(consumer_key=twitter_consumer_key, consumer_secret=twitter_consumer_secret, access_token_key=twitter_access_token, access_token_secret=twitter_access_secret)

statuses = twitter_api.GetUserTimeline(screen_name=handle, count=200, include_rts=False)

tag_list = ["Xmas", "Summer"]
for status in statuses:
  if (status.lang == 'en'):
    #assume there exists a hashtag in the tweet
    for hashtag in status.entities.hashtags:
      if hashtag.text in tag_list:
        print status
</code></pre>

python twitter