前回の投稿に引き続き今度はTwythonのDocumentを見ながら検索してみたり、タイムラインの情報を取得してみようと思います。
導入編のTwythonで遊ぼう その1はこちら
そしてTwythonからTwitterのApiをいじいじする練習をしてみます。
TwythonのDocumentationはこちらにあります。
https://twython.readthedocs.org/en/latest/api.html#core-interface
1 search(**params)をやってみる。
ということで検索のAPIをやってみたいと思います。
TwythonのDocumentationをクリックするとTwitterのAPIのページに飛びます。search(**params)のから飛ぶのはこちら
リンク先で確認するべきはPrametersの項目です。
例えば、qを見るとrequiredと書かれています。これはAPIを使うときに必ず必要になるよ。という意味です。Example Valuesを見るとどうやら検索したい単語を入れるみたいです。
今回は、countの項目も使ってみようと思います。これは検索して返って来る結果の個数を指定できます。デフォルトの場合は15個まで結果を返してくれます。
というわけでTwythonのexampleを書き換えてみましょう。
こちらがオリジナル。
from twython import Twython, TwythonError # Requires Authentication as of Twitter API v1.1 twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: search_results = twitter.search(q='WebsDotCom', count=50) except TwythonError as e: print e for tweet in search_results['statuses']: print 'Tweet from @%s Date: %s' % (tweet['user']['screen_nam\ e'].encode('utf-8'), tweet['created_at']) print tweet['text'].encode('utf-8'), '\n'
自分が勉強用に書き換えたのはこちら。
#coding: UTF-8 from twython import Twython, TwythonError # Requires Authentication as of Twitter API v1.1 APP_KEY='' APP_SECRET=' ' OAUTH_TOKEN='' OAUTH_TOKEN_SECRET='' twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: search_results = twitter.search(q='ドラゲナイ', count=100) except TwythonError as e: print e statuses_list = search_results['statuses'] for num in range(0, len(statuses_list)): text_in_tweet = statuses_list[num] print text_in_tweet['text']
qのところに自分の調べたい単語を入れて実行するといろいろと楽しめるんじゃないかとおもいますので是非試してみてください。
2 get_home_timeline(**params)をやってみる。
さてAPIいじりの練習をもう一度やってみましょう。今度は自分のタイムラインを表示してみましょう。コメントには私のメモ書きが入っています。
#coding: UTF-8 from twython import Twython, TwythonError import json APP_KEY='' APP_SECRET='' OAUTH_TOKEN='' OAUTH_TOKEN_SECRET='' twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: #自分の画面に表示されるタイムラインを取得する。 #countには取得するTweetの上限数を決めることができる。パラメータ設定しない場合は、デフォルトで20個が返ってくる。 #最大で指定できるのは200まで #返ってくるリストを格納 user_timeline = twitter.get_home_timeline(count = 200, exclude_replies = 'true') except TwythonError as e: print e #取得してきたツイートの数をカウントする。 print len(user_timeline) #帰ってきたリストの最初から最後までの数を発生させる。 for num in range(0, len(user_timeline)): #リストの中から一つずつ要素を取り出す。 text_of_tweet = user_timeline[num] #要素からテキストの部分を取り出して表示する。 print text_of_tweet['text']
3 まとめ
Twythonの扱い方としては、まずDocumentationで自分の扱ってみたい関数を調べて、twitterのAPIに飛びます。
そして、使いたい関数が必要とするParametersを調べて適切なvalueを与えてやることで自分の必要とする結果を得ることができます。