44with persistence between runs
55
66Usage:
7- python load_session_cookie.py # Use default LibreWolf
8- python load_session_cookie.py chrome # Use Chrome
7+ python load_session_cookie.py # Use default Chrome
98 python load_session_cookie.py firefox # Use Firefox
9+ python load_session_cookie.py librewolf # Use LibreWolf
1010
1111First run loads from browser and saves session.
1212Subsequent runs use saved session, fallback to browser if expired.
1313
14- $ python load_session_cookie.py
15- Instagram Cookie Authentication for instagrapi
16- =======================================================
17- Target browser: librewolf
18-
19-
20- No valid saved session found.
21- Loading fresh cookies from librewolf...
22- Loading cookies from librewolf...
23- Found X Instagram cookies in librewolf
24- Testing login with librewolf browser cookies...
25- Browser cookie login successful: @username
26- Saving session for future use...
27- Session saved to cookie_session.json
28-
29- Authentication successful!
30- Session saved for future use.
31-
3214"""
15+
3316import os
3417import sys
18+
3519from instagrapi import Client
3620
3721COOKIE_SESSION_FILE = "cookie_session.json"
3822
23+
3924def get_instagram_cookies_from_browser (browser_name ):
4025 """Get Instagram cookies from specified browser"""
4126 try :
4227 import browser_cookie3
4328 except ImportError :
44- print ("browser_cookie3 not installed. Install with: pip install browser_cookie3" )
29+ print (
30+ "browser_cookie3 not installed. Install with: pip install browser_cookie3"
31+ )
4532 return None
4633
47- # Map browser names to browser_cookie3 functions
4834 supported_browsers = {
4935 "brave" : browser_cookie3 .brave ,
5036 "chrome" : browser_cookie3 .chrome ,
@@ -65,14 +51,11 @@ def get_instagram_cookies_from_browser(browser_name):
6551
6652 try :
6753 print (f"Loading cookies from { browser_name } ..." )
68-
69- # Get raw browser cookies
7054 browser_cookies = list (supported_browsers [browser_name ]())
7155
72- # Filter for Instagram cookies
7356 instagram_cookies = {}
7457 for cookie in browser_cookies :
75- if ' instagram.com' in cookie .domain :
58+ if " instagram.com" in cookie .domain :
7659 instagram_cookies [cookie .name ] = cookie .value
7760
7861 print (f"Found { len (instagram_cookies )} Instagram cookies in { browser_name } " )
@@ -82,138 +65,94 @@ def get_instagram_cookies_from_browser(browser_name):
8265 print (f"Failed to load cookies from { browser_name } : { e } " )
8366 return None
8467
85- def test_browser_cookie_login (browser_name ):
86- """Test loading Instagram cookies from specified browser"""
87-
88- # Get cookies from browser
89- instagram_cookies = get_instagram_cookies_from_browser (browser_name )
90- if not instagram_cookies :
91- print (f"No Instagram cookies found in { browser_name } . Log into Instagram in { browser_name } first." )
92- return False
93-
94- if not instagram_cookies :
95- print (f"No Instagram cookies found in { browser_name } ." )
96- return False
97-
98- # Create instagrapi client and load cookies
99- cl = Client ()
100-
101- # Load cookies into instagrapi session
102- for cookie_name , cookie_value in instagram_cookies .items ():
103- cl .private .cookies .set (cookie_name , cookie_value , domain = 'instagram.com' )
10468
105- print (f"Testing login with { browser_name } browser cookies..." )
106-
107- # Try to access user info to test login
108- try :
109- user_info = cl .account_info ()
110- print (f"Success! Logged in as @{ user_info .username } " )
111- print (f"User ID: { user_info .pk } " )
112- return True
113-
114- except Exception as login_error :
115- print (f"Cookie login failed: { login_error } " )
116- print ("Cookies may be expired or browser session invalid." )
117- return False
118-
119- def test_saved_cookie_session ():
120- """Test if saved cookie session still works"""
69+ def load_saved_session ():
70+ """Try to load and validate a previously saved session"""
12171 if not os .path .exists (COOKIE_SESSION_FILE ):
122- return None # No saved session
72+ return None
12373
12474 try :
12575 print ("Trying saved cookie session..." )
12676 cl = Client ()
77+ cl .load_settings (COOKIE_SESSION_FILE )
12778
128- # Load saved session
129- session = cl .load_settings (COOKIE_SESSION_FILE )
130- cl .set_settings (session )
131-
132- # Test by trying to get account info
13379 user_info = cl .account_info ()
13480 print (f"Saved session works for @{ user_info .username } " )
13581 return cl
13682
13783 except Exception as e :
13884 print (f"Saved session expired: { e } " )
139- # Remove expired session file
14085 try :
14186 os .remove (COOKIE_SESSION_FILE )
14287 print ("Removed expired session file" )
143- except :
88+ except OSError :
14489 pass
14590 return None
14691
92+
14793def authenticate_with_browser_cookies (browser_name ):
14894 """Authenticate using browser cookies, save session if successful"""
149-
150- # Get cookies from browser
15195 instagram_cookies = get_instagram_cookies_from_browser (browser_name )
15296 if not instagram_cookies :
15397 return None
15498
155- # Create instagrapi client and load cookies
15699 cl = Client ()
157100
158- # Load cookies into instagrapi session
159101 for cookie_name , cookie_value in instagram_cookies .items ():
160- cl .private .cookies .set (cookie_name , cookie_value , domain = ' instagram.com' )
102+ cl .private .cookies .set (cookie_name , cookie_value , domain = " instagram.com" )
161103
162104 print (f"Testing login with { browser_name } browser cookies..." )
163105
164- # Try to access user info to test login
165106 try :
166107 user_info = cl .account_info ()
167108 print (f"Browser cookie login successful: @{ user_info .username } " )
168109
169- # Save successful session for next time
170110 print ("Saving session for future use..." )
171111 cl .dump_settings (COOKIE_SESSION_FILE )
172112 print (f"Session saved to { COOKIE_SESSION_FILE } " )
173113
174114 return cl
175115
176- except Exception as login_error :
177- print (f"Browser cookie login failed: { login_error } " )
116+ except Exception as e :
117+ print (f"Browser cookie login failed: { e } " )
178118 print ("Cookies may be expired or browser session invalid." )
179119 return None
180120
121+
181122def main ():
182123 """Main authentication function"""
183- # Default to LibreWolf if no arguments
184- browser_name = sys .argv [1 ] if len (sys .argv ) > 1 else "librewolf"
124+ browser_name = sys .argv [1 ] if len (sys .argv ) > 1 else "chrome"
185125
186126 print ("Instagram Cookie Authentication for instagrapi" )
187127 print ("=" * 55 )
188128 print (f"Target browser: { browser_name } " )
189129 print ()
190130
191- # Step 1: Try saved cookie session first
192- client = test_saved_cookie_session ()
131+ # Step 1: Try saved session first
132+ client = load_saved_session ()
193133
194134 if client :
195135 print ("\n Authentication successful using saved session!" )
196- print ("No need to load fresh cookies.\n " )
197136 return client
198137
138+ # Step 2: Try browser cookies
199139 print ("\n No valid saved session found." )
200140 print (f"Loading fresh cookies from { browser_name } ..." )
201141
202- # Step 2: Try browser cookies if saved session failed
203142 client = authenticate_with_browser_cookies (browser_name )
204143
205144 if client :
206145 print ("\n Authentication successful!" )
207146 print ("Session saved for future use.\n " )
208147 return client
209- else :
210- print ("\n Authentication failed." )
211- print (f"Please ensure you're logged into Instagram in { browser_name } ," )
212- print ("cookies are valid, and browser_cookie3 is installed.\n " )
213- return None
148+
149+ print ("\n Authentication failed." )
150+ print (f"Please ensure you're logged into Instagram in { browser_name } ," )
151+ print ("cookies are valid, and browser_cookie3 is installed.\n " )
152+ return None
153+
214154
215155if __name__ == "__main__" :
216- # Just run the authentication (don't exit on failure for integration)
217156 result = main ()
218157 if result is None :
219158 sys .exit (1 )
0 commit comments