Python twitter 検索APIでキーワード検索
twitter が用意してくれている検索APIをたたいてみます。
この手の記事はたくさんあるので、少し検索すればすぐに方法が見つかります。
#!/usr/bin/env python # -*- coding: utf-8 -*- from requests_oauthlib import OAuth1Session import json import secret # URL for keyword search url = 'https://api.twitter.com/1.1/search/tweets.json' keyword = 'Python' params = {'q': keyword, 'count': 10} # GET by OAuth twitter = OAuth1Session(secret.CK, secret.CS, secret.AT, secret.AS) req = twitter.get(url, params = params) if req.status_code == 200: timeline = json.loads(req.text) statuses = timeline['statuses'] for each in timeline['statuses']: print('-----') print(each['text']) else: print ("Error: %d" % req.status_code)
以下の4つの値については、スクリプトに直接記述する訳にはいかなかったので、別ファイル(secret.py)に入れて、読み込むようにしています。
取得方法については、
Twitterアプリケーションの作成(Consumer key、Consumer secret、Access token、Access token secretの確認方法)
CK: Consumer Key
CS: Consumer Secret
AT: Access Token
AS: Accesss Token Secert
とりあえず、キーワードは 'Python' で直接スクリプトに書いていますが、引数で渡すなりすれば良いと思います。
10件取得して、ツイート本文のみを出力しています。
実行結果
----- Top Stories, Jun 4-10: Did Python declare victory over R?; The Keras 4 Step Workflow https://t.co/NtfUBmnZDO ----- RT @nixcraft: "Haskell is faster than C++, more concise than Perl, more regular than Python, more flexible than Ruby, more typeful than C#,… ----- 😇 ☑ 😇 @timewith_uk need a Senior software engineer https://t.co/UzX2jm76UG #python #flask ----- tag yourself are you alm's inner conflict, lukas' anger, forsyth's anguish or python's chivalry https://t.co/6Hn3BsZhPs ----- Building your own cryptocurrency trading bot using Python and the Poloniex API https://t.co/KPoXcH5kXQ ----- Practical XGBoost in Python - 2.6 - Handle Imbalanced Dataset https://t.co/eWWkV1jRwY via @YouTube ----- Building your own cryptocurrency trading bot using Python and the Poloniex API: https://t.co/K8pBDkEnXM via @YouTube ----- RT @gp_pulipaka: Building a Serverless Alerting Chatbot with AWS Lex. #BigData #MachineLearning #DataScience #AI #CloudComputing #Serverles… ----- Network Test Engineer: Network Test Engineer (Mountain View, CA) Design, develop, modify, &/or test network needed… https://t.co/Fij8REd3ga ----- @Bugseedz @LOUwwHENRY @LeLapinTaquin Rien qu'au niveau du champ lexical utilisé on a compris d'où ça vient
たまに、キーワードが含まれていないものが出力されている気がするが何故だろう。