niiyan's blog

niiyanの個人ブログ。

tweepy を使って Twitter API で検索

とりあえず AviSynth 関連のツイートを取得することを目的としているので、Twitter API で検索する方法を調べた。

tweepy v1.5 documentation*1 によると、API.search() で検索ができるらしい。戻り値は、SearchResult オブジェクトのリスト(JSON ではない)。

以前保存しておいた tweepy v1.5 のドキュメントから引用(少し古いバージョンのものです):

API.search(q[, lang][, locale][, rpp][, page][, since_id][, geocode][, show_user])

Returns tweets that match a specified query.
Parameters:

q – the search query string
lang – Restricts tweets to the given language, given by an ISO 639-1 code.
locale – Specify the language of the query you are sending. This is intended for language-specific clients and the default should work in the majority of cases.
rpp – The number of tweets to return per page, up to a max of 100.
page – The page number (starting at 1) to return, up to a max of roughly 1500 results (based on rpp * page.
geocode – Returns tweets by users located within a given radius of the given latitude/longitude. The location is preferentially taking from the Geotagging API, but will fall back to their Twitter profile. The parameter value is specified by “latitide,longitude,radius”, where radius units must be specified as either “mi” (miles) or “km” (kilometers). Note that you cannot use the near operator via the API to geocode arbitrary locations; however you can use this geocode parameter to search near geocodes directly.
show_user – When true, prepends “:” to the beginning of the tweet. This is useful for readers that do not display Atom’s author field. The default is false.

Return type:

list of SearchResult objects

SearchResult オブジェクトがどんな属性を持っているのか tweepy のドキュメントを見てもわからず、小一時間調べる。python - Tweepy API: how to get a user's id from a status SearchResult object? - Stack Overflow とかで一部わかったが、まだ全体は見えず。

よくよく考えてみると、TwitterAPI を使いやすくしているライブラリなんだから、TwitterAPI のドキュメントを見ればいいかも、と気づく。

GET search | dev.twitter.com

全部使えるわけではないみたいだけど、「Example requests」のところが参考になった。

# モジュールのインポート
import tweepy
import urllib # URL エンコード

# Twitter の認証を行う
# auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# auth.set_access_token(access_key, access_secret)
# api = tweepy.API(auth)
api = tweepy.API() # Search API は認証不要

# 検索
query = u"foo" # クエリ
results = api.search(urllib.quote_plus(query.encode('utf-8')))

# 結果を整形
for result in results:
    print result.text # とりあえず表示するだけ

こんな感じで、つぶやきの本文を取り出すことはできた。

GET search | dev.twitter.com によると、Requires Authentication が false になっているので、Search API を使うだけなら認証は必要ないみたい。

また、クエリは URL エンコード必須で、複数のクエリを使用する場合は + で連結する必要がある。そのため、urllib.quote_plus() を使っている。OR 検索の場合は、"abc+OR+def" になる。

次回からは、

  • 取得したをデータベースに保存
  • データベースからデータを取得して表示

をやる予定。

*1:現在は削除されていて見られない。