Skip to content

Instantly share code, notes, and snippets.

@kjordahl
Last active October 7, 2015 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjordahl/392e1caf3eb0600bf24a to your computer and use it in GitHub Desktop.
Save kjordahl/392e1caf3eb0600bf24a to your computer and use it in GitHub Desktop.
Capture geolocated tweets through Twitter streaming API
import requests
from requests_oauthlib import OAuth1
import json
from my_auth import APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET
# Number of tweets to capture
MAX_COUNT = 1000
# New York City
west, south, east, north = -74.26, 40.48, -73.70, 40.92
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
r = requests.post('https://stream.twitter.com/1.1/statuses/filter.json',
data={'locations': '{},{},{},{}'.format(west, south, east, north)},
auth=auth, stream=True)
if r.ok:
count = 0
with open('tweets_raw.json', 'w') as f:
lines = r.iter_lines()
while count < MAX_COUNT:
line = lines.next()
if line:
f.write(line)
f.write('\n')
count += 1
else:
print('Status code {}: {}'.format(r.status_code, r.reason))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment