LoginSignup
8
11

More than 5 years have passed since last update.

PythonでInstagramAPIを使って画像取り込んだ

Last updated at Posted at 2018-04-19

Instagram APIとは

Instagram APIとはその名の通り、Instagramが提供するAPIです。
下記のデータの取得ができます(2018/4/19現在)。
データの取得方法はここを参照してください。

  • User
    • ユーザ自身の情報
    • ユーザ自身が投稿した最新のメディア
  • Media
    • 指定した場所の近くで投稿されたメディア
  • Comments
    • ユーザ自身が投稿したメディアについてコメント
  • Tags
    • 指定したタグオブジェクトの情報
    • タグの検索
    • 指定したタグがついたメディア
  • Locations
    • ロケーションの情報
    • 指定したロケーションで投稿されたメディア
    • ロケーションオブジェクトの検索

太字の機能のみ審査なしで利用可能です。

ファイル構造

root/
 ┣images/ #画像取り込むフォルダ
 ┣configs.py #ユーザ情報設定
 ┗api.py

ユーザ情報設定(configs.py)

configs.py
CLIENT_ID = "[]"
CLIENT_SECRET = "[]"
ACCESS_TOKEN = "[]"

画像取得プログラム(api.py)

api.py
from configs import *

import requests
from PIL import Image
from io import BytesIO

# APIのURL
url = "https://api.instagram.com/v1/users/self/media/recent/?access_token={}".format(ACCESS_TOKEN)

# レスポンス(JSON型)
response = requests.get(url).json()

# レスポンスに格納されている各データに対する処理
for d in response['data']:
    # 画像のID
    image_id = d['id']
    # 画像のURL
    image_url = d['images']['standard_resolution']['url']
    # 画像のURLからのレスポンス
    image_response = requests.get(image_url)
    # レスポンスを変換
    img = Image.open(BytesIO(image_response.content))
    # 保存
    img.save('images/%s.jpg' % (image_id), 'JPEG', quality=100, optimize=True)

これでimagesフォルダに自身の投稿メディアが保存されます。

8
11
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
8
11