Like instagram photo with selenium python Like instagram photo with selenium python selenium selenium

Like instagram photo with selenium python


First of all, in your case it is recommended to use the official Instagram Api for Python (documentation here on github).

It would make your bot much simpler, more readable and most of all lighter and faster. So this is my first advice.

If you really need using Selenium I also recommend downloading Selenium IDE add-on for Chrome here since it can save you much time, believe me. You can find a nice tutorial on Youtube.

Now let's talk about possible solutions and them implementations. After some research I found that the xpath of the heart icon below left the post behaves like that:The xpath of the icon of the first post is:

xpath=//button/span

The xpath of the icon of the second post is:

xpath=//article[2]/div[2]/section/span/button/span

The xpath of the icon of the third post is:

xpath=//article[3]/div[2]/section/span/button/span

And so on. The first number near "article" corresponds to the number of the post.

enter image description here

So you can manage to get the number of the post you desire and then click it:

def get_heart_icon_xpath(post_num):    """    Return heart icon xpath corresponding to n-post.    """    if post_num == 1:      return 'xpath=//button/span'    else:      return f'xpath=//article[{post_num}]/div[2]/section/span/button/span'try:    # Get xpath of heart icon of the 19th post.    my_xpath = get_heart_icon_xpath(19)    heart_icon = driver.find_element_by_xpath(my_xpath)    heart_icon.click()    print("Task executed successfully")except Exception:    print("An error occurred")

Hope it helps. Let me know if find other issues.


i'm trying to do the same)Here is a working method.
Firstly, we find a class of posts(v1Nh3), then we catch link attribute(href).

posts = bot.find_elements_by_class_name('v1Nh3')links = [elem.find_element_by_css_selector('a').get_attribute('href') for elem in posts]


I implemented a function that likes all the picture from an Instagram page. It could be used on the "Explore" page or simply on an user's profil page.

Here's how I did it.

First, to navigate to a profil page from Instagram's main page, I create a xPath for the "SearchBox" and a xPath to the element in the dropdown menu results corresponding to the index.

def search(self, keyword, index):    """ Method that searches for a username and navigates to nth profile in the results where n corresponds to the index"""            search_input = "//input[@placeholder=\"Search\"]"    navigate_to = "(//div[@class=\"fuqBx\"]//descendant::a)[" + str(index) + "]"    try:        self.driver.find_element_by_xpath(search_input).send_keys(keyword)        self.driver.find_element_by_xpath(navigate_to).click()        print("Successfully searched for: " + keyword)    except NoSuchElementException:        print("Search failed")

Then I open the first picture:

def open_first_picture(self):    """ Method that opens the first picture on an Instagram profile page """    try:                     self.driver.find_element_by_xpath("(//div[@class=\"eLAPa\"]//parent::a)[1]").click()    except NoSuchElementException:        print("Profile has no picture") 

Like each one of them:

def like_all_pictures(self):    """ Method that likes every picture on an Instagram page."""      # Open the first picture    self.open_first_picture()      # Create has_picture variable to keep track     has_picture = True         while has_picture:        self.like()        # Updating value of has_picture        has_picture = self.has_next_picture()    # Closing the picture pop up after having liked the last picture    try:        self.driver.find_element_by_xpath("//button[@class=\"ckWGn\"]").click()                        print("Liked all pictures of " + self.driver.current_url)    except:         # If driver fails to find the close button, it will navigate back to the main page        print("Couldn't close the picture, navigating back to Instagram's main page.")        self.driver.get("https://www.instagram.com/")def like(self):    """Method that finds all the like buttons and clicks on each one of them, if they are not already clicked (liked)."""    unliked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__outline__24__grey_9 u-__7\" and @aria-label=\"Like\"]//parent::button")    liked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__filled__24__red_5 u-__7\" and @aria-label=\"Unlike\"]")    # If there are like buttons    if liked:        print("Picture has already been liked")    elif unliked:        try:               for button in unliked:                button.click()        except StaleElementReferenceException: # We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.            print("Failed to like picture: Element is no longer attached to the DOM")

This method checks if picture has a "Next" button to the next picture:

def has_next_picture(self):    """ Helper method that finds if pictures has button \"Next\" to navigate to the next picture. If it does, it will navigate to the next picture."""    next_button = "//a[text()=\"Next\"]"    try:        self.driver.find_element_by_xpath(next_button).click()        return True    except NoSuchElementException:        print("User has no more pictures")        return False

If you'd like to learn more feel free to have a look at my Github repo: https://github.com/mlej8/InstagramBot