LoginSignup
5
8

More than 5 years have passed since last update.

Twitterの最新ツイートをストリーミングで取得する(2018年10月)

Last updated at Posted at 2018-10-08

概要

TwitterのAPIを使用して、ツイートのデータを取得する。
今回はストリームとして最新のツイートを継続的に取得する。

"Filter realtime Tweets"というAPIが用途に合っていそうなので、それを使う。
https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter

手順

APIキーの発行

Twitterの開発者アカウント(?)に登録した上で、APIを使ったアプリケーションの作成申請(?)が必要。いろいろ入力項目があり面倒だが、申請から登録完了までのタイムラグは無く、すぐに完了する。

ここの手順は割愛する。

実装(requests_oauthlib編)

TwitterのAPIに特化したサードパーティライブラリもあったが、まずは汎用的なrequests_oauthlibを使ってみる。

このスクリプトを実行すると、スクリプトは終了せず次々にデータが取得されて標準出力に表示される。

import json
import requests_oauthlib

uri = 'https://stream.twitter.com/1.1/statuses/filter.json'

# 自分の環境用に置き換える 
consumer_key = 'your consumer key'
consumer_secret = 'your consumer secret'
access_token = 'your access token'
access_token_secret = 'your access token secret'


def main():
    session = requests_oauthlib.OAuth1Session(
        consumer_key, consumer_secret, access_token, access_token_secret
    )
    # "Python"が含まれるツイートを取得. 'stream=True'は必須.
    r = session.post(uri, data=dict(track="Python"), stream=True)
    for line in r.iter_lines():
        status = json.loads(line.decode("utf-8"))
        for k, v in status.items():
            print(k, ":", v)
        print("------------------------------")


if __name__ == '__main__':
    main()

TwitterのAPIに特化したライブラリを使う

よく調べていないが、twitterというそのままな名前のライブラリが使えそうだった。
ツイートを単純に取得するにはrequests_oauthlibで十分だが、検索条件などを積極的に入れようと思った場合、専用のライブラリを使ったほうが便利なのかもしれない。

こちらの方の記事が参考になりそうでした。

参考資料

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8