Home > Back-end >  How to know if element appear and then disappear in selenium python ' is_displayed() issues �
How to know if element appear and then disappear in selenium python ' is_displayed() issues �

Time:02-23

In the website i'm trying to automate, when the internet connection get lost a notification you can access to it by a class name appears at the top of the page and tells you that there is no internet and i want to code something that let you pause the process until the internet get back and i'm tying to reack that by .is_displayed() which return a True value after checking that the notification appears and it's working fine but when i tried to check the disappear of the element it show me an error

except:
#time.sleep(3)
if driver.find_element(By.CLASS_NAME, "HGcYc4pY").size['width'] != 0 :
    print ('internet lost')
    while True:
        c= driver.find_element(By.CLASS_NAME, "HGcYc4pY").is_displayed()
        if driver.find_element(By.CLASS_NAME, "KhLQZTRq pxYtrw1j D56bmevE").is_displayed() == True:
            print("still lost")
        if driver.find_element(By.CLASS_NAME, "KhLQZTRq pxYtrw1j D56bmevE").is_displayed() == False:
            print("interent is back")
            break   
print("did it ")          

I tried this and it's just the same it doesn't work when the notification disappear aggain

except:
    #time.sleep(3)
    if driver.find_element(By.CLASS_NAME, "HGcYc4pY").size['width'] != 0 :
        print ('internet lost')
        while True:
            if driver.find_element(By.CLASS_NAME, "HGcYc4pY").size['width'] != 0:
                print("still lost")
            if driver.find_element(By.CLASS_NAME, "HGcYc4pY").size['width'] == 0:
                print("interent is back")
                break   
    print("did it ")     

CodePudding user response:

I could not reproduce that. I mean, I disconnected my PC from the internet and got the "no internet" page but I could not see there elements with class name HGcYc4pY.
Anyway, what I can suggest here is: instead of find_element method you can use find_elements method. It will always return you a list of elements found matching the passed locator. In case there was matches the list will be non-empty, otherwise the list will be empty. Python interprets empty list as a Boolean False while non-empty list is interpreted as a Boolean True.
This approach will never throw exception in case of no element found.
So, you logic could be something like this:

if driver.find_elements(By.CLASS_NAME, "HGcYc4pY"):
    #do whatever you need for the case the element is presented on the page
else:
    #do whatever you want for the no element presented case
  • Related