🚀 Facebook開発者アプリなしでInstagramにログイン&トークン取得する方法! 🎉
みなさん、InstagramのAPIを使いたいけど、Facebook開発者アプリを作るのが面倒…って思ったことありませんか? 🤔
「APIキーなしでInstagramにログインして、自動的にOTP認証を突破し、セッションIDとCSRFトークンを取得する」という魔法のようなスクリプトを紹介します! ✨💻
このスクリプトを使えば…
✅ Instagramに自動ログインできる!
✅ OTP(ワンタイムパスワード)認証も自動突破! 📩
✅ セッションID & CSRFトークンを取得して、APIリクエストに活用可能!
しかも… Facebook開発者アプリ不要! 😍
🎯 やることリスト(全体の流れ)
1️⃣ Seleniumを使ってInstagramにログイン 🖥️
2️⃣ もしOTP(セキュリティ認証)が必要なら、Gmailから自動取得! 📩
3️⃣ 取得したOTPを自動入力し、ログインを完了! ✅
4️⃣ セッションIDとCSRFトークンを取得し、API操作に活用!
🛠 事前準備(必要なもの)
まず、以下のものを用意してください!
✅ Python 3.x 🐍
✅ Selenium(ブラウザ自動化) 🌐
✅ WebDriver Manager(自動的にChromeDriverをインストール)
✅ IMAP対応のGmailアカウント(OTPを取得するため) 📩
🛠 まずは環境設定!
1️⃣ 必要なライブラリをインストール
pip install selenium webdriver-manager
🔹 selenium
→ ブラウザ自動化のためのライブラリ(Pythonでブラウザを操作する!)
🔹 webdriver-manager
→ ChromeDriverを自動ダウンロードしてくれる!(手動インストール不要!)
📌 1. Instagramのログイン情報を設定
# Instagramのアカウント情報
INSTAGRAM_USERNAME = "<あなたのInstagramのユーザー名>"
INSTAGRAM_PASSWORD = "<あなたのInstagramのパスワード>"
# Gmailのログイン情報(OTP取得用)
GMAIL_ADDRESS = "<あなたのGmailアドレス>"
GMAIL_PASSWORD = "<あなたのGmailのパスワード>"
IMAP_SERVER = "imap.gmail.com"
IMAP_PORT = 993
📍 この変数に自分のログイン情報を入力します。
🔹 INSTAGRAM_USERNAME
→ InstagramのログインID
🔹 INSTAGRAM_PASSWORD
→ Instagramのパスワード
🔹 GMAIL_ADDRESS
→ OTPを受信するGmailのアドレス
🔹 GMAIL_PASSWORD
→ Gmailのパスワード(IMAP認証に必要)
🔹 IMAP_SERVER
→ GmailのIMAPサーバー(Gmailの場合は "imap.gmail.com"
固定)
🔹 IMAP_PORT
→ IMAPのポート番号(993
はGmailの標準ポート)
📩 2. GmailからOTPを取得する関数
import re
import imaplib
import email
from email.header import decode_header
💡 ライブラリの説明
🔹 re
→ 正規表現を使うためのライブラリ(OTPの6桁コードを抽出するために使う!)
🔹 imaplib
→ IMAPを使ってメールを取得するライブラリ(Gmailのメールを読むために使う)
🔹 email
→ メールの解析をするライブラリ(メールの内容を取得&デコードする!)
🔹 decode_header
→ メールの件名の文字化け対策のために使う
📌 OTP(認証コード)をGmailから取得する関数
def fetch_verification_code():
"""
Instagramの認証コード(OTP)をGmailから取得する関数
"""
📍 この関数は、OTPが書かれたメールを検索し、6桁のコードを取得します!
📌 GmailのIMAPサーバーに接続
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT) # IMAPサーバーにSSL接続
mail.login(GMAIL_ADDRESS, GMAIL_PASSWORD) # Gmailにログイン
mail.select("inbox") # 受信ボックスを開く
🔹 IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
→ GmailのIMAPサーバーに接続
🔹 mail.login(GMAIL_ADDRESS, GMAIL_PASSWORD)
→ Gmailにログイン
🔹 mail.select("inbox")
→ 受信トレイを開く!
📌 Instagramからのメールを検索
status, messages = mail.search(None, '(UNSEEN FROM "no-reply@mail.instagram.com")')
📍 InstagramのOTPメールを検索する!
🔹 UNSEEN
→ 未読メールのみ検索!(過去のメールは無視)
🔹 FROM "no-reply@mail.instagram.com"
→ Instagramの公式メールアドレスからのメールを探す!
📌 メールの本文を解析&6桁のOTPを取得
for num in message_ids:
status, msg_data = mail.fetch(num, "(RFC822)") # メールのデータを取得
for response_part in msg_data:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1]) # メールデータをデコード
📍 メールの本文を解析し、6桁のOTPコードを抽出する!
code_match = re.search(r"\b\d{6}\b", body) # 6桁の数字を探す
if code_match:
otp_code = code_match.group(0) # OTPコードを取得
mail.logout()
return otp_code # OTPを返す!
🔹 正規表現(re.search(r"\b\d{6}\b", body)
)を使って、6桁の数字を抽出! ✅
🔹 OTPが見つかったら、それを返す! 🎉
🌐 3. SeleniumでInstagramに自動ログイン!
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
📍 Seleniumを使ってブラウザを自動操作するための準備!
🔹 webdriver
→ ブラウザの操作をするライブラリ
🔹 By
→ 要素を見つけるために使う(例:By.NAME
)
🔹 Keys
→ Enterキーなどを送信するために使う
🔹 Service
→ ChromeDriverの管理用
🔹 ChromeDriverManager
→ ChromeDriverを自動インストールしてくれる!
📌 Chromeブラウザを起動!
service = Service(ChromeDriverManager().install()) # ChromeDriverをインストール
options = webdriver.ChromeOptions()
# ブラウザの自動検出回避
options.add_argument("--start-maximized") # ウィンドウを最大化
options.add_argument("--disable-blink-features=AutomationControlled") # Selenium検出を防ぐ
📍 これでInstagramのログインページを開ける準備が完了! 🚀
📌 ログイン処理
driver.get("https://www.instagram.com/accounts/login/")
time.sleep(5)
# ユーザー名&パスワードを入力
username_input = driver.find_element(By.NAME, "username")
password_input = driver.find_element(By.NAME, "password")
username_input.send_keys(INSTAGRAM_USERNAME)
password_input.send_keys(INSTAGRAM_PASSWORD)
password_input.send_keys(Keys.RETURN)
🔹 Instagramのログインページを開く!
🔹 ユーザー名とパスワードを自動入力!
最終コード
# 必要なライブラリをインポート
import re
import time
import imaplib
import email
from email.header import decode_header
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# ---------------------------
# ユーザー設定
# ---------------------------
INSTAGRAM_USERNAME = "<あなたのInstagramユーザー名>" # Instagramのユーザー名
INSTAGRAM_PASSWORD = "<あなたのInstagramパスワード>" # Instagramのパスワード
GMAIL_ADDRESS = "<あなたのGmailアドレス>" # Gmailアドレス(OTP受信用)
GMAIL_PASSWORD = "<あなたのGmailパスワード>" # Gmailのパスワード
IMAP_SERVER = "imap.gmail.com"
IMAP_PORT = 993
# ---------------------------
# OTP取得関数
# ---------------------------
def fetch_verification_code():
"""
Gmailの受信トレイからInstagramのOTPコードを取得する関数
"""
try:
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
mail.login(GMAIL_ADDRESS, GMAIL_PASSWORD)
mail.select("inbox")
# 未読のInstagramのメールを検索
status, messages = mail.search(None, '(UNSEEN FROM "no-reply@mail.instagram.com")')
if status != "OK":
print("📭 メール検索に失敗しました。")
return None
message_ids = messages[0].split()
for num in message_ids:
status, msg_data = mail.fetch(num, "(RFC822)")
if status != "OK":
continue
for response_part in msg_data:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1])
# メール本文を取得
body = ""
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True).decode(errors="ignore")
break
else:
body = msg.get_payload(decode=True).decode(errors="ignore")
# OTPコード(6桁の数字)を取得
code_match = re.search(r"\b\d{6}\b", body)
if code_match:
otp_code = code_match.group(0)
mail.logout()
return otp_code
mail.logout()
except Exception as e:
print("⚠️ OTP取得エラー:", e)
return None
return None
# ---------------------------
# Instagramログイン関数
# ---------------------------
def login_instagram():
"""
Seleniumを使用してInstagramにログインし、OTP認証が必要な場合はGmailから自動取得して入力する
"""
service = Service(ChromeDriverManager().install())
options = webdriver.ChromeOptions()
# Selenium検出防止設定
options.add_argument("--start-maximized")
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(service=service, options=options)
try:
driver.get("https://www.instagram.com/accounts/login/")
time.sleep(5)
# ユーザー名とパスワードを入力
username_input = driver.find_element(By.NAME, "username")
password_input = driver.find_element(By.NAME, "password")
username_input.send_keys(INSTAGRAM_USERNAME)
password_input.send_keys(INSTAGRAM_PASSWORD)
password_input.send_keys(Keys.RETURN)
time.sleep(7)
# OTP認証が必要か確認
if "challenge" in driver.current_url:
print("🔐 OTP認証が必要!")
time.sleep(30)
otp_code = fetch_verification_code()
if otp_code:
print(f"✅ OTP取得成功!コード: {otp_code}")
otp_input = driver.find_element(By.NAME, "security_code")
otp_input.clear()
otp_input.send_keys(otp_code)
otp_input.send_keys(Keys.RETURN)
time.sleep(7)
else:
print("❌ OTPの取得に失敗しました。手動で入力してください。")
input("OTPを手動で入力し、続行するにはEnterキーを押してください...")
# クッキーからセッションIDとCSRFトークンを取得
cookies = driver.get_cookies()
session_id = None
csrf_token = None
for cookie in cookies:
if cookie["name"] == "sessionid":
session_id = cookie["value"]
if cookie["name"] == "csrftoken":
csrf_token = cookie["value"]
if session_id and csrf_token:
print("✅ ログイン成功!")
print(f"🌟 セッションID: {session_id}")
print(f"🔑 CSRFトークン: {csrf_token}")
# セッション情報を保存
with open("instagram_session.txt", "w") as f:
f.write(f"Session ID: {session_id}\nCSRF Token: {csrf_token}\n")
return session_id, csrf_token
else:
print("❌ ログイン失敗。セッションクッキーが見つかりませんでした。")
return None, None
finally:
print("📌 ブラウザを閉じます...")
driver.quit()
# ---------------------------
# メイン実行
# ---------------------------
if __name__ == "__main__":
session_id, csrf_token = login_instagram()
if session_id:
print("✅ APIリクエストにこのセッションIDを使用できます:", session_id)
else:
print("❌ ログインに失敗しました。手動で試してください。")
✅ まとめ
✨ Instagramに自動ログイン!
📩 GmailからOTPを取得&自動入力!
🔥 API操作に使えるセッショントークンを取得!
🚀 このスクリプトを使えば、InstagramのAPI制限を回避して色々な操作が可能になります!