DEV Community

Cover image for Instagram Automation using Python and Selenium
Saurabh Kumar
Saurabh Kumar

Posted on

Instagram Automation using Python and Selenium

In this tutorial, I have used Python and Selenium. I am assuming that you know the basics of Python.

In case, if you don't have Python installed, you can download it from https://www.python.org/ and follow the install instruction.

After Python, we need to install Selenium Automation Framework. We will be using pip to install Selenium.

python3 -m pip install Selenium
Enter fullscreen mode Exit fullscreen mode

Next, we will need to install ChromeDriver. You can download it from https://chromedriver.chromium.org/downloads. After downloading, unzip it and move it to some sensible location.

Automate Instagram

import os
from typing import KeysView
from selenium import webdriver
from selenium.webdriver.common import keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

os.environ['PATH'] += r"C:\Users\saura\Desktop"  #replace it with path that contains ChromeDriver
driver = webdriver.Chrome()

driver.get("https://www.instagram.com/?hl=en")

driver.implicitly_wait(5)

try:
    username = driver.find_element_by_name("username")
    password = driver.find_element_by_name("password")
except:
    print("no element found with this name")

username.send_keys("your_username")  #replace it with your instagram username
password.send_keys("your_password")  #replace it with your instagram password
password.send_keys(Keys.RETURN)

try:
    not_now = driver.find_element_by_class_name("cmbtv")
except:
    print("no element with this class name")

not_now.click()

try:
    not_now2 = driver.find_element_by_class_name("HoLwm")
except:
    print("no element with this class name")

not_now2.click()

see_all = driver.find_element_by_link_text("See All")
see_all.click()

for i in range(1, 30):
    follow_link = driver.find_element_by_xpath(f"html/body/div/section/main/div/div[2]/div/div/div[{i}]/div[3]")
    follow_link.click()
Enter fullscreen mode Exit fullscreen mode

Copy this code and paste it in your Python file with (.py) extension. Replace path to ChromeDriver and username and password in code. And then run it. It is completely automated. Just sit back and relax.

Top comments (0)