How to locate Instagram Follow button with selenium (Python)


I’m trying to locate the ‘follow’ button element on an instagram page (using selenium).

I’ve found the main ‘follow’ button of a user’s page ( with the following code:

follow_button = self.driver.find_element_by_css_selector('button')

Although after clicking the above element ^, now I’m trying to locate ‘follow’ buttons visible when you view a user’s followers.
Click here to see which buttons I’m referring to.

I’ve tried the following code but it doesn’t work:

acc_follow_buttons = self.driver.find_elements_by_css_selector('button')

for acc in acc_follow_buttons[:15]: 

I’ve also tried searching with Xpath, with no luck.

Could anyone with experience in Selenium help me with the code to locate the follow buttons on this page.

Asked By: Luke



I don’t have an Instagram account so I’m answering somewhat blind, but do the follow buttons have classes? If so then you can use driver.find_elements_by_class_name() to find the specific buttons.

Answered By: nbbbrewer

try this. range here points to number of followers.add a code to get follower count and append it to range.note that, list starts from 1.

for i in range(1, 10):
                follow = driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/ul/div/li[{}]/div/div[3]/button'.format(i))
Answered By: Prem Ib

You have to search for the button by button text:

Follow_Button = driver.find_element_by_xpath("//*[text()='Follow']")
Answered By: Tommaso Montagni

Without having to check if a element exist or not, check if the ds_user_id cookie is in the cookies.

# make a function to check if instagram is logged in
def is_logged_in():

  # getting instagram so we only have instagram cookies in driver.get_cookies()

  # get all the cookies, this returns a list of dicts
  cookies = driver.get_cookies()

  # loop through all the cookies till we find some cookie has ds_user_id in its name
  # to return True, but if the loop finished without finding one it will return False
  for cookie in cookies:
    if cookie['name'] == 'ds_user_id':
      return True
  return False

Very fast and better way.

Answered By: Kh4lid MD