Search code examples
pythonseleniumselenium-webdriverweb-scrapinginstagram

How can I like a picture on Instagram using its link with the help of Selenium (Python)?


My purpose was to write a program that could log in to Instagram and then like a picture using a certain link. And in the end, it should make a screenshot. The main trouble is that if the program gets a link for a second time my browser logs out of Instagram so I can't get a like on a photo. I've been searching for any decisions, but I found nothing about my problem. Please, help! Here's my code.

import time
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome('chromedriver.exe')
driver.get('https://www.instagram.com')


def log_in(un, pw):
    username = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='username']")))
    username.clear()
    for i in un:
        time.sleep(0.01)
        username.send_keys(i)

    password = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='password']")))
    password.clear()
    for i in pw:
        time.sleep(0.01)
        password.send_keys(i)

    login_button = WebDriverWait(driver, 2).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()

    driver.get('https://www.instagram.com/p/CSXFbIKjKxO/?utm_source=ig_web_copy_link')
    driver.find_elements_by_link_text('Like').click()
    filename = un + '.png'
    driver.save_screenshot(filename)


log_in('login', 'password')
driver.close()

Solution

  • The like web element is basically a svg element, you could try the below xpath :

    //*[name()='svg' and @aria-label='Like']
    

    in code, replace this :

    driver.find_elements_by_link_text('Like').click()
    

    to

    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[name()='svg' and @aria-label='Like']"))).click()