简体   繁体   中英

How to check if an element is not displayed in selenium python

How could I check to see if an element is not displayed. I would think it looks something like this.

if(element.is_not_displayed):
    doSomething()
else
    doSomethingElse()

To start with, there is no is_not_displayed attribute in Selenium .

To simulate a similar logic, instead of an if-else loop you may use a try-except{} loop inducing WebDriverWait for the invisibility_of_element() and you can use the following Locator Strategy :

try:        
    WebDriverWait(driver, 30).until(EC.invisibility_of_element(element))
    doSomething()
except TimeoutException:
    doSomethingElse()

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
from selenium.common.exceptions import TimeoutException

You have to use until_not as shown bellow

WebDriverWait(driver, "time you want to wait".until_not(EC.presence_of_element_located((By.ID,"someID")))

Example:

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID,"transpdiv-0"))) #here yout wait to the element appear

WebDriverWait(driver, 300).until_not(EC.presence_of_element_located((By.ID,"transpdiv-0"))) #here you wait the element disappear

Note: you have to add the same imports like undetect Selenium says:

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

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