Python Forum
Click Element if displayed using Selenium and Python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html)
+--- Thread: Click Element if displayed using Selenium and Python (/thread-14969.html)



Click Element if displayed using Selenium and Python - giaco__mar - Dec-27-2018

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?


RE: Click Element if displayed using Selenium and Python - metulburr - Dec-27-2018

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.