Python Forum

Full Version: Click Element if displayed using Selenium and Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys, I'm coding a script in which, when a button is clicked, sometimes a div appears and others it doesn't.
I'm trying to handle this exception using the following code

for i, j  in zip(range(160), tag):

    if i%10  == 0:
      url_to_search = "https://www.instagram.com/explore/tags/" + j + "/"
      driver.get(url_to_search)
      element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".v1Nh3.kIKUG._bz0w")))
      element.click() #Click prima foto

      element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".oW_lN._0mzm-.sqdOP.yWX7d")))
      element.click() #Click follow
      
      checkFo = driver.find_element_by_class_name(".aOOlW.HoLwm")

      if checkFo.is_displayed():
          checkFo.click
          
      else:
          element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".HBoOv.coreSpriteRightPaginationArrow")))
          element.click() #Click arrow

    else:
          element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".oW_lN._0mzm-.sqdOP.yWX7d")))
          element.click() #Click follow
          
          if checkFo.is_displayed():
              checkFo.click
          
          else:
              element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".HBoOv.coreSpriteRightPaginationArrow")))
              element.click() #Click arrow
              
          time.sleep(3)
But it doesn't work! The shell gives me this error:
Unable to locate element: {"method":"class name","selector":".aOOlW.HoLwm"}
Can anybody help me?
You can try waiting to make sure that element is up before, or try an ID instead. You wait for the others, but are not waiting for the one that is giving you an error.