Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toshihikoyanase/5769634 to your computer and use it in GitHub Desktop.
Save toshihikoyanase/5769634 to your computer and use it in GitHub Desktop.
Twitter Streaming APIを叩いて、Geoタグ付きのツイートを収集するPythonスクリプト
#!/usr/bin/env python
import tweepy
import datetime
import time
# See http://blog.unfindable.net/archives/4257
locationsL=[-180,-90,180,90]
class StreamListener(tweepy.StreamListener):
def __init__(self, api=None):
tweepy.StreamListener.__init__(self, api)
d = datetime.date.today()
self.out_prefix = "./filter"
self.fout = open("%s-%s.jsonl" % (self.out_prefix, d.isoformat()), 'a' )
self.day = d.day
def on_data(self, data):
if self.day != datetime.date.today().day:
self.fout.close()
self.fout = open("%s-%s.jsonl" % (self.out_prefix, d.isoformat()), 'a' )
if data.startswith("{"):
self.fout.write(data + "\n")
def on_timeout(self):
self.fout.close()
raise Exception
consumer_key = ""
consumer_secret = ""
access_token = ""
access_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
stream = tweepy.Stream(auth, StreamListener())
while True:
try:
stream.filter(locations=locationsL)
except Exception:
time.sleep(60)
stream = tweepy.Stream(auth, StreamListener())
@toshihikoyanase
Copy link
Author

元にしたプログラムのURLは http://blog.unfindable.net/archives/4257

変更したところは

  • 1日ごとに別のファイルに保存するようにした
  • 再接続の仕組みをPythonスクリプト内で導入した

インストール方法は

  • tweepyをインストールする pip install tweepy
  • twitter_streaming_filter_with_retry.pyをデータを収集するディレクトリTWEET_DIRに設置する

使い方は、

  • consumer_key, consumer_secret, access_token, access_secretを入力
  • locationsLに、緯度経度を指定する
  • cd $TWEET_DIR
  • python twitter_streaming_filter_with_retry.py
  • $TWEET_DIRにfilter-YYYY-MM-DD.jsonlというファイルでデータが保存される
  • 以上

出力形式は、

  • 1行に1つのツイートがJSON形式で保存される
  • Pythonなら1行読んでjson.loads(line.strip())とすると元のハッシュに戻すことができる

気をつけるところは

  • 同じユーザで複数個走らせても、一つを残して切断される
  • 保存ファイル名が直書き
  • エラーが起きたら問答無用で再接続しようとするので、プログラムの不具合の場合には、エラーも表示されずにデータが取得できない。
  • プロキシ内からのpipでのインストールは、 --proxy=username:password@proxy.server.name:proxyport オプションをつける

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment