Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Like instagram photo with selenium python

I'm trying to code my own bot python selenium bot for instagram to experiment a little. I succeeded to log in and to search an hashtag in the search bar which lead me to the following web page: web page

But I can not figure out how to like the photos in the feed, i tried to use a search with xpath and the following path: "//[@id="reactroot"]/section/main/article/div1/div/div/div1/div1/a/div" But it didn't work, does anybody have an idea?

like image 256
Valentin Mercier Avatar asked Sep 02 '25 03:09

Valentin Mercier


1 Answers

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.

like image 70
Federico Rubbi Avatar answered Sep 04 '25 23:09

Federico Rubbi