Home > Enterprise >  Python Selenium: Using css, how do I make an if else statement?
Python Selenium: Using css, how do I make an if else statement?

Time:12-19

I'm trying to make an if else that checks whether the css exists.

If the first css doesnt exist, it should click on the second css.

This is what I have:

    
#IF STATEMENT
      driver.find_element_by_css_selector('.GA_Track_Action_Download-FullHD-1080p > .movieQuality').click()
 
#ELSE STATEMENT
      driver.find_element_by_css_selector('.GA_Track_Action_Download-4K-2160p > .movieQuality').click()
    

What I tried:

if is_element_exist(driver, '.GA_Track_Action_Download-FullHD-1080p > .movieQuality''):
      driver.find_element_by_css_selector('.GA_Track_Action_Download-FullHD-1080p > .movieQuality').click()

else:
      driver.find_element_by_css_selector('.GA_Track_Action_Download-4K-2160p > .movieQuality').click()

Doesn't seem to be working.

CodePudding user response:

Try like below and confirm.

Get the Element in a List and check if the List is Empty or not. if the Length of the List is 0, the statements in the else block will be exceuted.

if len([driver.find_element(By.CSS_SELECTOR,".GA_Track_Action_Download-FullHD-1080p > .movieQuality")]) > 0:
    driver.find_element(By.CSS_SELECTOR, ".GA_Track_Action_Download-FullHD-1080p > .movieQuality").click()

else:
    driver.find_element(By.CSS_SELECTOR,".GA_Track_Action_Download-4K-2160p > .movieQuality").click()

CodePudding user response:

Instead of a if-else block use a try-except{} block and catch the exception to invoke the click on the second element as follows:

try:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".GA_Track_Action_Download-4K-2160p > .movieQuality"))).click()
except TimeoutException:
    driver.find_element(By.CSS_SELECTOR,".GA_Track_Action_Download-4K-2160p > .movieQuality").click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

CodePudding user response:

try:
    driver.find_element(By.CSS_SELECTOR,".GA_Track_Action_Download-FullHD-1080p > .movieQuality,.GA_Track_Action_Download-4K-2160p > .movieQuality").click()
except:
    pass

Why not just use ,(OR) to check for either.

  • Related