├── requirements.txt ├── images ├── Cookies.jpg └── Action Blocked - Error.jpeg ├── LICENSE ├── Scripts ├── saved_posts.py ├── highlights.py ├── posts.py └── stories.py ├── .gitignore └── README.md /requirements.txt: -------------------------------------------------------------------------------- 1 | instaloader==4.10 2 | retrying==1.3.4 3 | urllib3==2.1.0 4 | requests==2.31.0 5 | -------------------------------------------------------------------------------- /images/Cookies.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isPique/Instaloader-Scripts/HEAD/images/Cookies.jpg -------------------------------------------------------------------------------- /images/Action Blocked - Error.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isPique/Instaloader-Scripts/HEAD/images/Action Blocked - Error.jpeg -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 isPique 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Scripts/saved_posts.py: -------------------------------------------------------------------------------- 1 | import instaloader 2 | import os 3 | 4 | instance = instaloader.Instaloader() 5 | 6 | # Personal account is not recommended. To use it, simply create a new account. 7 | username = "YOUR INSTAGRAM USERNAME HERE" 8 | password = "YOUR INSTAGRAM PASSWORD HERE" 9 | 10 | instance.compress_json = False 11 | 12 | # Check if you have a session file to load, if not, login using credentials 13 | try: 14 | instance.load_session_from_file(username, "cookies.txt") 15 | 16 | except FileNotFoundError: 17 | try: 18 | instance.login(username, password) 19 | 20 | except: 21 | # If login fails, load the session using sessionid and csrftoken (not recommended if you use VPN) 22 | instance.load_session(username, {"sessionid": "YOUR SESSION ID HERE", "csrftoken": "YOUR CSRFTOKEN HERE"}) 23 | 24 | # Save the session to a file for future use 25 | instance.save_session_to_file("cookies.txt") 26 | 27 | if instance.context.is_logged_in: 28 | print(f"Logged as {username}") 29 | 30 | else: 31 | print("An error occurred while logging into the account.") 32 | 33 | profile = instaloader.Profile.from_username(instance.context, username) 34 | 35 | instance.download_saved_posts() 36 | 37 | # Delete unwanted files 38 | for root, dirs, files in os.walk(username): 39 | for file in files: 40 | if file.endswith((".xz", ".txt", ".json")): 41 | os.remove(os.path.join(root, file)) 42 | print(f"Deleting: {file}") -------------------------------------------------------------------------------- /Scripts/highlights.py: -------------------------------------------------------------------------------- 1 | import instaloader 2 | import os 3 | 4 | instance = instaloader.Instaloader() 5 | 6 | # Personal account is not recommended. To use it, simply create a new account. 7 | username = "YOUR INSTAGRAM USERNAME HERE" 8 | password = "YOUR INSTAGRAM PASSWORD HERE" 9 | 10 | instance.compress_json = False 11 | 12 | # Check if you have a session file to load, if not, login using credentials 13 | try: 14 | instance.load_session_from_file(username, "cookies.txt") 15 | 16 | except FileNotFoundError: 17 | try: 18 | instance.login(username, password) 19 | 20 | except: 21 | # If login fails, load the session using sessionid and csrftoken (not recommended if you use VPN) 22 | instance.load_session(username, {"sessionid": "YOUR SESSION ID HERE", "csrftoken": "YOUR CSRFTOKEN HERE"}) 23 | 24 | # Save the session to a file for future use 25 | instance.save_session_to_file("cookies.txt") 26 | 27 | if instance.context.is_logged_in: 28 | print(f"Logged as {username}") 29 | 30 | else: 31 | print("An error occurred while logging into the account.") 32 | 33 | # Enter the username with the highlights you want to download 34 | user = "" 35 | profile = instaloader.Profile.from_username(instance.context, username = user) 36 | 37 | os.makedirs(user, exist_ok = True) 38 | os.chdir(user) 39 | 40 | # Get the user's highlights and download them 41 | for highlight in instance.get_highlights(user = profile): 42 | for item in highlight.get_items(): 43 | instance.download_storyitem(item, '{}/{}'.format(highlight.owner_username, highlight.title)) 44 | 45 | # Delete unwanted files 46 | def delete_files_with_specific_extensions(folder_path, extensions): 47 | for root_folder, _, files in os.walk(folder_path): 48 | for file in files: 49 | file_extension = file.split(".")[-1] 50 | if file_extension in extensions: 51 | file_path = os.path.join(root_folder, file) 52 | try: 53 | os.remove(file_path) 54 | print(f"{file_path} deleted.") 55 | except Exception as e: 56 | print(f"Error occurred while deleting {file_path}: {e}") 57 | 58 | os.chdir("..") 59 | folder_path = user 60 | extensions = ["xz", "txt", "json"] 61 | 62 | delete_files_with_specific_extensions(folder_path, extensions) -------------------------------------------------------------------------------- /Scripts/posts.py: -------------------------------------------------------------------------------- 1 | import instaloader 2 | import os 3 | 4 | instance = instaloader.Instaloader() 5 | 6 | # Personal account is not recommended. To use it, simply create a new account. 7 | username = "YOUR INSTAGRAM USERNAME HERE" 8 | password = "YOUR INSTAGRAM PASSWORD HERE" 9 | 10 | instance.compress_json = False 11 | 12 | # Check if you have a session file to load, if not, login using credentials 13 | try: 14 | instance.load_session_from_file(username, "cookies.txt") 15 | 16 | except FileNotFoundError: 17 | try: 18 | instance.login(username, password) 19 | 20 | except: 21 | # If login fails, load the session using sessionid and csrftoken (not recommended if you use VPN) 22 | instance.load_session(username, {"sessionid": "YOUR SESSION ID HERE", "csrftoken": "YOUR CSRFTOKEN HERE"}) 23 | 24 | # Save the session to a file for future use 25 | instance.save_session_to_file("cookies.txt") 26 | 27 | if instance.context.is_logged_in: 28 | print(f"Logged as {username}") 29 | 30 | else: 31 | print("An error occurred while logging into the account.") 32 | 33 | while True: 34 | username = input("Enter any username you want: ") 35 | print("The account you are looking for is being searched in Instagram's database..") 36 | 37 | try: 38 | try: 39 | profile = instaloader.Profile.from_username(instance.context, username) 40 | if profile and profile.mediacount > 0: 41 | print("Account found. Downloading posts.. ") 42 | instance.download_profile(username) 43 | print("The download process has been completed.") 44 | 45 | # Delete unwanted files 46 | for root, dirs, files in os.walk(username): 47 | for file in files: 48 | if file.endswith((".xz", ".txt", ".json")): 49 | os.remove(os.path.join(root, file)) 50 | print(f"Deleting: {file}") 51 | 52 | elif profile and profile.mediacount == 0: 53 | print("There are no posts in the account you are looking for.") 54 | 55 | except instaloader.exceptions.PrivateProfileNotFollowedException: 56 | print("This is a private account. You need to follow it to access its posts.") 57 | 58 | except instaloader.exceptions.ProfileNotExistsException: 59 | print("The account you are looking for is not exists on instagram. Try another username") -------------------------------------------------------------------------------- /Scripts/stories.py: -------------------------------------------------------------------------------- 1 | from urllib3 import exceptions 2 | from retrying import retry 3 | import instaloader 4 | import requests 5 | import os 6 | 7 | instance = instaloader.Instaloader() 8 | 9 | # Personal account is not recommended. To use it, simply create a new account. 10 | username = "YOUR INSTAGRAM USERNAME HERE" 11 | password = "YOUR INSTAGRAM PASSWORD HERE" 12 | 13 | instance.compress_json = False 14 | 15 | # Check if you have a session file to load, if not, login using credentials 16 | try: 17 | instance.load_session_from_file(username, "cookies.txt") 18 | 19 | except FileNotFoundError: 20 | try: 21 | instance.login(username, password) 22 | 23 | except: 24 | # If login fails, load the session using sessionid and csrftoken (not recommended if you use VPN) 25 | instance.load_session(username, {"sessionid": "YOUR SESSION ID HERE", "csrftoken": "YOUR CSRFTOKEN HERE"}) 26 | 27 | # Save the session to a file for future use 28 | instance.save_session_to_file("cookies.txt") 29 | 30 | if instance.context.is_logged_in: 31 | print(f"Logged as {username}") 32 | 33 | else: 34 | print("An error occurred while logging into the account.") 35 | 36 | while True: 37 | username = input("Enter any username you want: ") 38 | print("The account you are looking for is being searched in Instagram's database..") 39 | 40 | try: 41 | try: 42 | try: 43 | profile = instaloader.Profile.from_username(instance.context, username) 44 | if profile and profile.has_viewable_story: 45 | print("Account found. Downloading stories.. ") 46 | for story in instance.get_stories(profile.username): 47 | for item in story.get_items(): 48 | instance.download_storyitem(item, ':stories') 49 | print("The download process has been completed.") 50 | 51 | # Delete unwanted files 52 | for root, dirs, files in os.walk(username): 53 | for file in files: 54 | if file.endswith((".xz", ".txt", ".json")): 55 | os.remove(os.path.join(root, file)) 56 | print(f"Deleting: {file}") 57 | 58 | elif profile and not profile.has_viewable_story: 59 | print("There are no viewable story in the account you are looking for.") 60 | 61 | except exceptions.ConnectTimeoutError: 62 | @retry(wait_exponential_multiplier = 1000, wait_exponential_max = 10000, stop_max_attempt_number = 5) 63 | def make_api_request(): 64 | response = requests.get(f"https://i.instagram.com/api/v1/users/web_profile_info/?username={username}") 65 | response.raise_for_status() 66 | return response.json() 67 | 68 | try: 69 | data = make_api_request() 70 | except Exception as e: 71 | print(f"Error: {e}") 72 | 73 | except instaloader.exceptions.PrivateProfileNotFollowedException: 74 | print("This is a private account. You need to follow it to access its stories.") 75 | 76 | except instaloader.exceptions.ProfileNotExistsException: 77 | print("The account you are looking for is not exists on instagram. Try another username") -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Instaloader Auxiliar Scripts 2 | Here, you'll find some scripts that download an Instagram account's posts, stories, etc. 3 | 4 | > [!IMPORTANT] 5 | > * Instaloader is constantly improving and evolving, and adapting its code to platform changes. This implies that some endpoints may change, and some of the scripts may stop working. 6 | > * The objective of this repository is to serve as an example, it has educational purposes, and in no case does it pretend to be perfect or fully functional. 7 | > * Please, see: [Instaloader](https://instaloader.github.io/) 8 | 9 | # INSTALLATION 10 | 11 | 1. Clone the repository: 12 | ```bash 13 | git clone https://github.com/isPique/Instaloader-Scripts.git 14 | ``` 15 | 16 | 2. Navigate to the project directory: 17 | ```bash 18 | cd Instaloader-Scripts 19 | ``` 20 | 21 | 3. Install required libraries 22 | ```bash 23 | pip install -r requirements.txt 24 | ``` 25 | 26 | # Usage 27 | 28 | > [!WARNING] 29 | > Please make sure you don't use a VPN before running the script, because if you do, this happens; 30 | 31 | ![Action Blocked](https://github.com/isPique/Instaloader-Scripts/blob/main/images/Action%20Blocked%20-%20Error.jpeg) 32 | 33 | * Anyways. You'll need to set up a few things before running the script. 34 | 35 | * Set your own Instagram username and password on `posts.py`, `stories.py` and `highlights.py` (personal account not recommended just create a new account). If you want to download your personal account's saved posts, you can use your personal account on `saved_posts.py`. 36 | 37 | * If you get an error like `JSON Query to accounts/login/: Could not find "window._sharedData" in html response.` (which will happen with a 99% probability), you can login with your cookies. 38 | 39 | ## How to log in with cookies? 40 | 41 | **1- Login to Instagram**: Login to Instagram in your browser with your username and password. 42 | 43 | **2- Open Developer Tools**: In most web browsers, you can access developer tools by right-clicking on a webpage and selecting "Inspect" or "Inspect Element." Alternatively, you can press F12 or Ctrl+Shift+I to open developer tools. 44 | 45 | **3- Navigate to the Application or Storage Tab**: In the developer tools window, there should be a tab called "Application" or "Storage" (the exact name may vary depending on the browser). Click on it. 46 | 47 | **4- Expand Cookies**: In the Application or Storage tab, you'll find a section for "Cookies" in the left sidebar. Expand this section by clicking on it. 48 | 49 | **5- Find the Cookie for Instagram**: Look for the https://www.instagram.com/ link. Click on it to view the cookies. 50 | 51 | **6- Find the Session ID and CSRF Token**: In the list of cookies you should see one labeled "Session ID" or something similar. The name of the session cookie may vary depending on the website or application you are using. The value of this cookie is your session ID. Likewise, in the list of cookies, you should see one labeled "CSRF Token" or something similar. The value of this cookie is your CSRF (Cross-Site Request Forgery) Token. 52 | 53 | * After following all these steps you should see something like this; 54 | 55 | ![Cookies](https://github.com/isPique/Instaloader-Scripts/blob/main/images/Cookies.jpg) 56 | 57 | * Set your own **username**, **password**, **Session ID**, **CSRF Token**, and the **username of the person who has the posts you want to download** in the script you intend to use and run the script. You'll see that the posts start to download in the directory where you run the script. 58 | 59 | * Additionally, when you run the script, it saves your cookies to a text file named `cookies.txt`. This means you won't need to use your credentials in subsequent runs. The script logs in with the cookie file in second and subsequent executions. 60 | 61 | # 62 | 63 | > [!TIP] 64 | > If you're using the firefox browser, you can use the code below to get the `cookies.txt` file. 65 | 66 | ```py 67 | from argparse import ArgumentParser 68 | from glob import glob 69 | from os.path import expanduser 70 | from platform import system 71 | from sqlite3 import OperationalError, connect 72 | 73 | try: 74 | from instaloader import ConnectionException, Instaloader 75 | except ModuleNotFoundError: 76 | raise SystemExit("Instaloader not found.\n pip install [--user] instaloader") 77 | 78 | 79 | def get_cookiefile(): 80 | default_cookiefile = { 81 | "Windows": "~/AppData/Roaming/Mozilla/Firefox/Profiles/*/cookies.sqlite", 82 | "Darwin": "~/Library/Application Support/Firefox/Profiles/*/cookies.sqlite", 83 | }.get(system(), "~/.mozilla/firefox/*/cookies.sqlite") 84 | cookiefiles = glob(expanduser(default_cookiefile)) 85 | if not cookiefiles: 86 | raise SystemExit("No Firefox cookies.sqlite file found. Use -c COOKIEFILE.") 87 | return cookiefiles[0] 88 | 89 | 90 | def import_session(cookiefile, sessionfile): 91 | print("Using cookies from {}.".format(cookiefile)) 92 | conn = connect(f"file:{cookiefile}?immutable=1", uri=True) 93 | try: 94 | cookie_data = conn.execute( 95 | "SELECT name, value FROM moz_cookies WHERE baseDomain='instagram.com'" 96 | ) 97 | except OperationalError: 98 | cookie_data = conn.execute( 99 | "SELECT name, value FROM moz_cookies WHERE host LIKE '%instagram.com'" 100 | ) 101 | instaloader = Instaloader(max_connection_attempts=1) 102 | instaloader.context._session.cookies.update(cookie_data) 103 | username = instaloader.test_login() 104 | if not username: 105 | raise SystemExit("Not logged in. Are you logged in successfully in Firefox?") 106 | print("Imported session cookie for {}.".format(username)) 107 | instaloader.context.username = username 108 | instaloader.save_session_to_file(sessionfile) 109 | 110 | 111 | if __name__ == "__main__": 112 | p = ArgumentParser() 113 | p.add_argument("-c", "--cookiefile") 114 | p.add_argument("-f", "--sessionfile") 115 | args = p.parse_args() 116 | try: 117 | import_session(args.cookiefile or get_cookiefile(), args.sessionfile) 118 | except (ConnectionException, OperationalError) as e: 119 | raise SystemExit("Cookie import failed: {}".format(e)) 120 | ``` 121 | 122 | * Example usage: 123 | ```bash 124 | python whatever_you_named_your_file.py --sessionfile "path\to\your\Instaloader Scripts\cookies.txt" 125 | ``` 126 | --------------------------------------------------------------------------------