LoginSignup
2
1

More than 1 year has passed since last update.

InstaloaderでInstagramから画像を取得する

Posted at

機械学習で画像のデータセットが必要な時、GoogleだけでなくInstagramから取得したい。
でも、APIを使うのは申請とかあって面倒くさそう。。。
スクレイピングでやるのも面倒くさい。。。

そんな方向けに、Instagramから簡単に画像をダウンロードできるInstaloaderを紹介します。
なお、本当はハッシュタグから画像を検索してダウンロードしたかったのですが、、、2022年7月8日現在、バグが発生しており使えません。。。
また、Instagrams自体は、このような手法でデータを取得することを認めていないようです。場合によってはアカウントがロックされる可能性もあるかもしれませんので、各自の責任で実行してください。

環境

Windows10
anaconda=4.13.0
python=3.10.5

セットアップ

まずはInstaloaderをインストールします。

pip install instaloder

準備はこれだけ!

コード

instaloader.py
import sys
import instaloader

def main():
    TARGET_ID = <データを取得したいInstaアカウントのID>
    USER_ID = <ご自身のアカウントID>
    PASSWORD = <ご自身のパスワード>
    number_of_picture = 300 # 取得したい画像枚数

    cls = GetImageFromInstagram(USER_ID, PASSWORD)
    cls.download_user_posts(TARGET_ID, number_of_picture)

    # 以下、現在バグのため動きません
    # hashtag = <取得したいハッシュタグ>
    # cls.download_hashtag_posts(hashtag)

class GetImageFromInstagram():
    def __init__(self, my_user_name, password):
        self.L = instaloader.Instaloader()
        self.my_user_name = my_user_name
        self.password = password
        self.L.login(my_user_name, password)

    def download_user_posts(self, target_username, limitation=100):
        posts = instaloader.Profile.from_username(self.L.context, target_username).get_posts()

        for index, post in enumerate(posts, 1):
            self.L.download_post(post, target_username)
            if index >= limitation:
                print(f'{target_username}の画像を{limitation}枚保存しました。')
                break

    def download_hashtag_posts(self, hashtag, limitation=100):
        posts = instaloader.Hashtag.from_name(self.L.context, hashtag).get_posts()
        for index, post in enumerate(posts, 1):
            self.L.download_post(post, target='#' + hashtag)
            if index >= limitation:
                print(f'ハッシュタグ#{hashtag}の画像を{limitation}枚保存しました。')
                break

if __name__ == '__main__':
    main()

ログインしなくても動きはします。
が、、、僕のときは途中で止まりました。
ブラウザからInstagramを開いた時も、ログインしていないと途中で見れなくなるので、おそらく同じような仕組みが働いているのだと思います。

実際に動かしてみる

私の推しのれなひょんのInstagramから画像を取得します。
image.png
アカウントIDはrenamatsui27、27は7月27日生まれなのでその数字ですね。
pythonファイルを動かすと同じディレクトリ内にrenamatusi27とインスタのアカウント名でフォルダが作成され、その中にダウンロードしたデータが格納されます。
シンプルで簡単ですね。
image.png
投稿データ全体を取得します。jsonファイル、テキストファイル、動画なんかも含まれます。
必要に応じて、適宜削除してください。

Instaloaderめっちゃ便利です。
ぜひ試してみてください!

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