Like instagram pictures using Selenium and Python

With over a billion users, Instagram is a popular social media platform. While it provides APIs for certain interactions, developers often use web automation tools like Selenium to interact with Instagram programmatically. This article demonstrates how to automate liking Instagram pictures using Python and Selenium.

Important: This tutorial is for educational purposes only. Always respect Instagram's terms of service and avoid spam-like behavior that could result in account restrictions.

Prerequisites and Setup

Before starting, you need Python and Selenium installed on your system. Install Selenium using pip ?

pip install selenium

You'll also need to download ChromeDriver from the official Chrome Developer website and ensure it's in your system PATH or specify its location in your script.

Basic Instagram Automation Setup

Selenium allows us to control a web browser programmatically. Here's how to set up the basic framework for Instagram automation ?

Importing Required Libraries

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

Login to Instagram

# Initialize the Chrome driver
driver = webdriver.Chrome()

# Navigate to Instagram
driver.get('https://www.instagram.com/')

# Wait for page to load
time.sleep(3)

# Find and fill username field
username_field = driver.find_element(By.NAME, 'username')
username_field.send_keys('your_username')

# Find and fill password field
password_field = driver.find_element(By.NAME, 'password')
password_field.send_keys('your_password')

# Submit the login form
password_field.send_keys(Keys.RETURN)

# Wait for login to complete
time.sleep(5)

Method 1: Liking Pictures from a User Profile

This method navigates to a specific user's profile and likes their recent posts ?

# Navigate to a specific user's profile
driver.get('https://www.instagram.com/username_here')
time.sleep(3)

# Find the first few posts
posts = driver.find_elements(By.CSS_SELECTOR, 'article div div div div a')[:3]

for post in posts:
    # Click on the post to open it
    post.click()
    time.sleep(2)
    
    try:
        # Find and click the like button
        like_button = driver.find_element(By.CSS_SELECTOR, '[aria-label="Like"]')
        like_button.click()
        print("Post liked successfully")
    except:
        print("Post already liked or like button not found")
    
    # Close the post modal
    close_button = driver.find_element(By.CSS_SELECTOR, 'svg[aria-label="Close"]')
    close_button.click()
    time.sleep(2)

Method 2: Liking Pictures by Hashtag

This approach searches for posts using a specific hashtag and likes them ?

# Navigate to hashtag page
hashtag = "python"
driver.get(f'https://www.instagram.com/explore/tags/{hashtag}/')
time.sleep(3)

# Find posts in the hashtag feed
posts = driver.find_elements(By.CSS_SELECTOR, 'article div div div div a')[:5]

for i, post in enumerate(posts):
    try:
        # Click on the post
        post.click()
        time.sleep(2)
        
        # Like the post
        like_button = driver.find_element(By.CSS_SELECTOR, '[aria-label="Like"]')
        like_button.click()
        print(f"Liked post {i+1}")
        
        # Close the post
        close_button = driver.find_element(By.CSS_SELECTOR, 'svg[aria-label="Close"]')
        close_button.click()
        time.sleep(2)
        
    except Exception as e:
        print(f"Error with post {i+1}: {str(e)}")
        continue

Method 3: Limited Liking with Error Handling

This method includes better error handling and limits the number of likes to avoid spam detection ?

def like_posts_safely(driver, max_likes=3):
    liked_count = 0
    
    # Find available posts
    posts = driver.find_elements(By.CSS_SELECTOR, 'article div div div div a')
    
    for post in posts[:max_likes]:
        if liked_count >= max_likes:
            break
            
        try:
            # Click to open post
            post.click()
            WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, '[aria-label="Like"]'))
            )
            
            # Check if already liked
            like_button = driver.find_element(By.CSS_SELECTOR, '[aria-label="Like"]')
            
            if like_button:
                like_button.click()
                liked_count += 1
                print(f"Successfully liked post {liked_count}")
                
            # Close post modal
            close_button = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, 'svg[aria-label="Close"]'))
            )
            close_button.click()
            
            # Random delay to mimic human behavior
            time.sleep(3)
            
        except Exception as e:
            print(f"Error processing post: {str(e)}")
            continue
    
    return liked_count

# Usage
total_liked = like_posts_safely(driver, max_likes=3)
print(f"Total posts liked: {total_liked}")

Best Practices and Considerations

Practice Recommendation Reason
Rate Limiting Add delays between actions Avoid spam detection
Error Handling Use try-catch blocks Handle UI changes gracefully
Headless Mode Run browser in background Better performance
User-Agent Rotation Change browser signatures Appear more human-like

Important Notes

Instagram frequently updates its interface, which may break CSS selectors used in these examples. Always test your scripts and be prepared to update selectors as needed. Additionally, excessive automation may trigger Instagram's anti-bot measures, potentially leading to account restrictions.

Remember to close the browser driver when finished ?

# Clean up
driver.quit()

Conclusion

Selenium provides powerful web automation capabilities for Instagram interactions. Use these techniques responsibly, respecting platform guidelines and implementing proper rate limiting. Always prioritize ethical automation practices to maintain account security.

---
Updated on: 2026-03-27T08:17:30+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements