LoginSignup
0
1

More than 1 year has passed since last update.

Pythonでリブログやスキを一括取得する方法

Last updated at Posted at 2021-02-17

ここではTumblrのリブログなどを一括取得できるPyTumblrを紹介します。

まず、コマンドラインで以下のようにしてインストールします。

pip install pytumblr

Tumblrを外部から操作する場合はアプリを登録しAPIを使う必要があります。 https://www.tumblr.com/oauth/apps からアプリを登録してください。

コンシューマーキーやコンシューマーシークレットを取得して、以下のようにすると初期化できます。

import pytumblr

client = pytumblr.TumblrRestClient(
    TUMBLR_CONSUMER_KEY,
    TUMBLR_CONSUMER_SECRET,
    user.tumblr_access_token,
    user.tumblr_secret_key
)

TUMBLR_CONSUMER_KEY, TUMBLR_CONSUMER_SECRET,user.tumblr_access_token, user.tumblr_secret_keyは自分のものに変更しておいてください。Webサービスなど不特定多数のユーザーのアクセストークンを必要とする場合はDjangoでTwitterなどのOAuth 1.0認証を行う方法を見て取得してください。

使い方は公式ドキュメントを見てもらうこととして、以下ではリブログやスキを一括取得する方法を紹介します。
とりあえずコードです。

offset = 0

def fetch_tumblr_reblogs(client):
    while True:
        response = client.posts("blog_name", limit=20, offset=offset, reblog_info=True)

        # Get the 'posts' field of the response
        posts = response['posts']

        #それ以上投稿がない場合
        if not posts:
            break

        for post in posts:
            #isReblog
            if 'reblogged_from_id' in post:
                print(post)

        offset += len(posts)

blog_nameの部分はリブログを取得したいブログのURL(https://www.tumblr.com/blog/***)の***の部分を入力してください。
TumblrのAPIは「最新20件を取得」などはできず一番古い投稿から順に取得していきます。offsetを設定すると一番古い投稿からoffset件飛ばして投稿を取得できます。

スキを取得するには以下のように少し変更します。

offset = 0

def fetch_tumblr_reblogs(client):
    while True:
        response = client.likes(limit=20, offset=offset)

        # Get the 'posts' field of the response
        posts = response['liked_posts']

        #それ以上投稿がない場合
        if not posts:
            break

        for post in posts:
            print(post)

        offset += len(posts)

宣伝

以上のコードを使ってRemind ArchivesというWebサービスを作りました。これは過去のいいねやRTをランダムに表示して発見とセレンディピティを生み出すことを目的とするサービスです。

0
1
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
0
1