TwitterのタイムラインをHTML形式で出力する

TwitterのタイムラインをHTML形式で出力するサンプルコードを作成してみた。

使用ライブラリはtweepy。tweepyの使用方法やアクセスキーの取得方法はtwitterAPI用pythonライブラリtweepyを使えるようになるまで。を参考にした。

以下のコードをファイルに保存し、APIアクセス用の各種キーを設定した上で実行すると、ファイルと同じフォルダに「tweets.html」という名前でアクセスキー取得時のアカウントのホームタイムラインが保存される。

注意:

# -*- coding: utf-8 -*-
from __future__ import with_statement
import tweepy

# Twitter APIへのアクセスに必要な各種キー。
consumer_key = 'consumer_key'
consumer_secret = 'consumer_secret'
access_key = 'access_key'
access_secret = 'access_secret'

def print_timeline(title, tweets):
    """ツイートをHTML形式で出力する。今回はサンプルなのでエスケープは行っていないが、通常は必ずエスケープすべき。"""
    with open('tweets.html', 'w') as f:
        f.write('<html><head>')
        f.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">')
        f.write('<title>%s</title>' % title)
        f.write('</head><body>')
        f.write('<dl>')
        for tweet in tweets:
            author = tweet.author
            f.write('<dt><img src="%s" />@%s</dt>' % (author.profile_image_url, author.screen_name))
            f.write('<dd>%s</dd>' % tweet.text)
        f.write('</dl>')
        f.write('</body></html>')

if __name__ == '__main__':
    # OAuth handler の生成。                                                      
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    # アクセストークンを OAuth handlerに設定。
    auth.set_access_token(access_key, access_secret)
    # API の生成。                         
    api = tweepy.API(auth_handler=auth)
    
    # ホームタイムラインの取得。
    tweets = api.home_timeline();
    #ホームタイムラインを整形して出力。
    print_timeline('ホームタイムライン', tweets)

補足:
tweepyでツイートからユーザ情報を参照するには「author」属性を使用します。
Twitter APIが出力するXML/JSON上は「author」ではなく「user」という名称になっていますが(GET statuses/home_timeline)、tweepy API上は「author」を使用するのが正しいようです。(「user」もあるが多分Depricated扱い)