Instagram Bot in Python.
About the project: This is project for a Python Instagram Bot.
This will use a web automation library to perform tasks on Instagram.
For this project, we'll use the selenium library, which allows you to control a web browser programmatically.
This is a powerful tool for automating web tasks like logging in, clicking buttons, and navigating pages.
Before you run the code:
- Install: Install selenium: Open your terminal or command prompt and run:
pip install selenium
- ChromeDriver: https://chromedriver.chromium.org/
- GeckoDriver (for Firefox): https://github.com/mozilla/geckodriver/releases
Make sure the driver is in your system's PATH or in the same directory as your script.
How to use this program:
- The provided script will prompt you for your Instagram username and password in the console.
- It will then open a Chrome browser window, navigate to Instagram, and attempt to log you in.
This is a simple template to get you started. From here, you could add more features like navigating to a specific user's profile, liking posts, or following other users by using selenium to find and interact with different elements on the page.
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# instagram_bot.py
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 selenium.common.exceptions import NoSuchElementException, TimeoutException
import time
import getpass # For securely getting the password without it showing in the console
def login_to_instagram(username, password, driver):
"""
Automates the login process for Instagram.
"""
try:
print("Navigating to Instagram...")
driver.get("https://www.instagram.com")
# Wait for the page to load and find the username input field
time.sleep(5)
username_field = driver.find_element(By.NAME, "username")
password_field = driver.find_element(By.NAME, "password")
print("Entering credentials...")
username_field.send_keys(username)
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN)
# Wait for the login to complete and the homepage to load
time.sleep(10)
# Check if login was successful by looking for a specific element on the homepage
try:
driver.find_element(By.XPATH, "//div[text()='Not Now']")
print("Login successful.")
except NoSuchElementException:
print("Login failed. Check your credentials.")
return False
return True
except NoSuchElementException:
print("Login fields not found. Instagram's page layout may have changed.")
return False
except TimeoutException:
print("Timeout while trying to load the page.")
return False
except Exception as e:
print(f"An unexpected error occurred during login: {e}")
return False
def main():
"""
Main function to run the Instagram Bot.
"""
print("--- Python Instagram Bot ---")
# Get user credentials
username = input("Enter your Instagram username: ").strip()
# Use getpass to securely enter the password
password = getpass.getpass("Enter your Instagram password: ").strip()
# Create a Service object for the ChromeDriver
# Ensure the path to your chromedriver is correct
# Example: service = Service("/path/to/your/chromedriver")
try:
service = Service("chromedriver") # Assuming chromedriver is in PATH or current directory
driver = webdriver.Chrome(service=service)
except Exception as e:
print(f"Error starting the WebDriver: {e}")
print("Please make sure you have the correct WebDriver installed and in your system's PATH.")
return
try:
# Perform the login
if login_to_instagram(username, password, driver):
print("You are now logged in. The bot will close in 10 seconds.")
# Now you can add more bot functionality here!
# Example: Go to a specific profile
# time.sleep(5)
# driver.get(f"https://www.instagram.com/{username}")
# time.sleep(10)
time.sleep(10)
else:
print("Failed to log in. Exiting.")
finally:
# Always close the browser window
driver.quit()
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()
← Back to Projects