简体   繁体   中英

How to click the second element if the first element is not clickable using Python Selenium

How to click the second element if the first element is not clickable using Python Selenium

Code trials:

if self.driver.find_element(By.CSS_SELECTOR, ".estimator-container:nth-child(3) .btn").is_not_clicked():
    self.driver.find_element(By.LINK_TEXT, "Dont have the Plate?").click();

To click on any clickable element you need to induce WebDriverWait for the element_to_be_clickable() wrapping up the the code block within a try-except{} block and you can usethe following Locator Strategies :

try:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".estimator-container:nth-child(3) .btn"))).click()
    print("First element was clicked")
except TimeoutException:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Dont have the Plate?"))).click()
    print("Second element was clicked")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM