Instagram Automation Bot in Python Using Selenium (Educational Project)
Web automation is a valuable skill for Python developers who want to understand how browsers work behind the scenes. In this educational project, you’ll learn how to build a basic Instagram automation bot using Python and Selenium. The goal of this project is to demonstrate browser automation concepts such as locating elements, handling input fields, and navigating web pages.
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.
Important Disclaimer
This project is intended strictly for educational and learning purposes. Automating interactions on websites like Instagram may violate their terms of service. You should always review and comply with the platform’s official policies before using automation tools. The author does not encourage misuse or abusive automation.
What You Will Learn From This Project
- How browser automation works using Selenium
- How to locate web elements using XPath and name attributes
- How to automate login workflows safely
- How to handle delays and page loading
- How web automation scripts are structured in Python
Before you run the code:
- Install: Install selenium: Open your terminal or command prompt and run:
pip install selenium
- ChromeDriver: ChromeDriver official website
- GeckoDriver (for Firefox): GeckoDriver official website
Make sure the driver is in your system's PATH or in the same directory as your script.
Why Use Selenium for Web Automation?
Selenium is a popular automation framework that allows Python programs to control real web browsers. It is commonly used for testing web applications, automating repetitive tasks, and learning how modern websites function. Because Selenium interacts with actual browser elements, it provides a realistic automation experience.
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 by using selenium to find and interact with different elements on the page.
To extend this project for learning purposes, you can experiment with:
- Navigating to different public pages
- Extracting publicly visible profile information
- Practicing element detection and page scrolling
- Improving error handling when elements are missing
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()
Frequently Asked Questions
Is this Instagram bot safe to use?
This script is meant for learning Selenium automation concepts. Always follow Instagram’s terms of service when experimenting with automation.
Do I need prior Selenium experience?
Basic Python knowledge is enough. This project helps beginners understand Selenium fundamentals.
Can this script stop working?
Yes. Websites frequently change their layouts, which may require updating element selectors.
← Back to Projects
