The purpose is I want to check the button is exist on web page and then click it, if not exist, just skip. But, it's not works if not 'is_displayed()', please suggest me how can I modify the code, thanks!
Here is the code:
button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ra_on"]')))
if button.is_displayed() == True:
button.click() #means turn to ON. It's works.
else:
print('It's ON ready.') #means turn ON ready. It's not works.
CodePudding user response:
Use find_elements
that will return a list of Web element
, if found at least one Web element
, if it does not find anything the list
will be empty.
Code:
try:
if len(driver.find_elements(By.XPATH, "//*[@id='ra_on']")) > 0:
print("element must be displayed, do whatever you wanna do here")
button = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='ra_on']")))
button.click()
else:
print("Element with xpath //*[@id='ra_on'] not found.")
except:
print("Just skip it")
pass
CodePudding user response:
To click on the button if it is clickable or else just to skip you can wrap up the line within a try-except{}
block and you can use the following solution:
try:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ra_on"]'))).click()
except TimeoutException:
pass
Note: You have to add the following imports :
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC