Choosing elements with Selenium on Instagram

Currently, I'm in the process of developing an Instagram bot that will automatically like images by identifying the 'heart element' on the webpage and clicking on it.

Upon inspection, I noticed that the structure of the element looked like this:

<div class="eo2As ">
<section class="ltpMr Slqrh">
<a class="fr66n tiVCN" href="#" role="button">
<span class="Szr5J coreSpriteHeartOpen ">Like</span></a>

The class values remain consistent for all unliked heart elements throughout the page.

This is my current code snippet:

from selenium import webdriver
username = "----"
password = "----" #values from original file

getdriver = ("https://www.instagram.com/accounts/login/")

driver = webdriver.Chrome(r'C:\testDir\chromedriver_win32\chromedriver.exe')
driver.get(getdriver)

driver.find_element_by_xpath("//input[@name='username']").send_keys(username)
driver.find_element_by_xpath("//input[@name='password']").send_keys(password)
driver.find_element_by_xpath("//button[contains(.,'Log in')]").click()

#Everything working fine up to this point

like = driver.find_element_by_css_selector('.Szr5J.coreSpriteHeartOpen')

for x in range(0,len(like)):
    if like[x].is_displayed():
        like[x].click()

However, I keep encountering the following error message:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".Szr5J.coreSpriteHeartOpen"}

I've experimented with different combinations of class names but haven't been able to find a solution yet!

If you have any insights or suggestions, they would be greatly appreciated!

Answer №1

Consider trying these options:

# The script may be too quick and attempting to locate the element before the page is fully loaded. Using `WebDriverWait` can help with this issue
like = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.Szr5J.coreSpriteHeartOpen')))

or:

import time

time.sleep(5) # Pause for 5 seconds after logging into Instagram
like = driver.find_element_by_css_selector('.Szr5J.coreSpriteHeartOpen')

If I understand correctly, you want to find all 'hearts' on the page. In that case, you should use

driver.find_elements_by_css_selector
like so:

# Returns an array of elements found
like = driver.find_elements_by_css_selector('.Szr5J.coreSpriteHeartOpen')

You can then iterate through these elements using a loop.

Here is the complete working code:

username = "----"
password = "----" # These values are from the original file

getdriver = ("https://www.instagram.com/accounts/login/")

driver = webdriver.Chrome(r'C:\testDir\chromedriver_win32\chromedriver.exe')
driver.get(getdriver)

driver.find_element_by_xpath("//input[@name='username']").send_keys(username)
driver.find_element_by_xpath("//input[@name='password']").send_keys(password)
driver.find_element_by_xpath("//button[contains(.,'Log in')]").click()

# Close the popup that appears after login
popup = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//div/div/button[contains(., Close)]'))
driver.find_element_by_xpath("//div/div/button[contains(., Close)]").click()

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.Szr5J.coreSpriteHeartOpen')))
# Find all 'hearts' on the page
likes = driver.find_elements(By.CSS_SELECTOR, ".Szr5J.coreSpriteHeartOpen")
print(len(likes))
print("WORKS")

for x in range(0,len(likes)):
    if likes[x].is_displayed():
        likes[x].click()
        print(x)

Output:

3
WORKS
0
1
2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating Element Attribute with Selenium in Python

Currently, I am utilizing python selenium to streamline data input on a specific website. The challenge lies in the fact that one of the fields restricts characters to a maximum length of "30". <input data-qa="input-LogId" data-testid="input-LogId" ...

An error occurred while attempting to execute a Selenium test, specifically a TypeLoadException for 'OpenQA.Selenium.Support.UI.WebDriverWait'

I've encountered an issue while running my selenium webdriver tests from a user control I created. The error message states: "An exception of type 'System.TypeLoadException' occurred in UserCreationFrontEnd.exe but was not handled in user co ...

What is the best way to loop through and access every link within a list using Python and Selenium? How can I programmatically click on each individual link found on a Yelp

I'm really interested in exploring all the links on this Yelp page that mention Dumplings in their link text. Check out the picture of the list of Yelp links Below is the code I've been using. I managed to reach the second page, but I'm st ...

Error: The utf-8 codec is unable to decode byte 0xd5 at position 3362 due to an invalid continuation byte

Recently, I encountered an issue while trying to execute a previously working script: import csv from selenium import webdriver from time import sleep from parsel import Selector from selenium.webdriver.common.keys import Keys from collections import defa ...

Python - Reading webpage content without specifying the URL

Attempting to create a Python program that can log in to Gmail and read the inbox page, I've made an attempt using Selenium and urllib2. As a beginner with these tools, here is what I came up with: from requests import session from selenium import we ...

Tallying the number of divs on a webpage every 3 seconds

I have a question regarding web scraping for tracking the quantity of specific items being dropped on a website. I am using Beautiful Soup to parse the HTML and find the number of div elements related to these items. However, when executing my code, it c ...

An error occurred while using GeckoDriver and Tor browser with Selenium Java: org.openqa.selenium.WebDriverException - [Exception... "Component not initialized" is encountered

While attempting to run Selenium with the Tor Browser, I encountered an error. Upon starting my code, the Tor Browser successfully opens and directs to the URL . However, instead of executing the last command with "sendKeys", the following error occurs: Ex ...

When operating in Jenkins or headless mode, Selenium/Katalon may encounter difficulties retrieving the text of a web element

My button displays the text <span _ngcontent-c4="" class="btn__text">FOO</span> When I run my Katalon (6.3.3) test locally, everything works fine. However, when running it in Jenkins, the text "FOO" is loaded as an empty string. To capture the ...

Error encountered while attempting to load token from file in the Discord.py event loop closing phase

As a precautionary measure, I've decided to keep my token in a separate file named token.txt. To load the token from the file and run the bot, I'm using the following code: f = open("token.txt", "r") token = f.readline() f.clo ...

How can I resolve a timeout error when encountering it while utilizing the chromedriver in Selenium?

It seems like I may be overlooking something simple here, as I have already tried numerous solutions without success. Being new to selenium, I am facing an issue that I cannot seem to resolve. Upon navigating to a web page using get(), I consistently encou ...

Remove an additional bracket from a given list

I am working with a list in Python that looks like this: results = [[['New','York','intrepid', 'bumbling']], [['duo', 'deliver', 'good', 'one']]] My goal is to transform it i ...

Get the numbers extracted from text using .text function in Selenium and perform a click and hold action

Is there a way to extract the numerical value from an element with text that includes a number followed by "px"? I specifically need to retrieve only the integer part of the number. Another question I have is related to selecting a random point or locatio ...

The WebDriver encountered an error while trying to click on an element

When using Selenium WebDriver, I am facing an issue with selecting an item from a drop-down list. The element I want to click on is labeled as "game club". Despite attempting to select different elements, I keep encountering an error stating that none of ...

The @FindBy annotation in Webelement fails to return a valid reference, resulting in a

When I try to invoke the method Spage.editExButton(int ID), I encounter an issue where WebElement first is null and an error occurs. I have already defined it using the @FindBy annotation, so why is it still null? To work around this problem, I have to exp ...

Is it possible to determine the current version of the Chrome driver dynamically while running a Selenium WebDriver test?

Is there a method to validate the compatibility of Chrome driver version at runtime? If the local machine's Chrome driver version is compatible, the script will proceed with its execution. Otherwise, it should fall back on the Chrome driver included i ...

Connect the wordNet sense key to VerbNet for mapping purposes

Is there a method in NLTK for retrieving the verb class id based on the WordNet sense key? As an illustration: how would one extract the verb class id from this particular WordNet sense key: take.v.01 ...

Unable to click on the Edit button on Facebook using the Selenium automation tool

https://i.stack.imgur.com/Hjh2w.png I am struggling to click on this button using XPATH. Previously, I was successful with the XPATH below but now it doesn't work: XPATH: /html/body/div[1]/div/div[1]/div/div[3]/div/div/div[2]/div/div/div[1]/div[1]/ ...

Help with selenium web scraping

In the month of June, I came across a question on assistance needed to scrape a website using Selenium in Python. Having tried the code back then and running into issues now, it seems like there might have been some changes to the site being scraped. The ...

Nested while loop in Python

I encountered an issue with my code when trying to complete a specific exercise. The exercise required me to create a program that would generate 100 random numbers in the range of 1-1000, then keep count of how many of those numbers were even and how many ...

How to manage auto suggestions in the "origin" and "destination" fields for the webpage "https://www.goibibo.com/" using Selenium

How can I handle auto suggestions in the "from" and "destination" boxes on the website "https://www.goibibo.com/" using Selenium? Please assist. I have tried using the basic method but I am unable to locate the XPath of the auto suggestion drop down. I a ...