1

So im running this piece of code, basically you enter a code and press a button and then the page redirects if the code is correct.

So i want the code to detect if an image on that page disappears using "invisibility_of_element_located" (So that i can tell if the page has loaded) which works fine when used alone, however i want to use it in an if statement, such that if the element does go invisible:

print(something)

However i cant seem to figure out how to set it up in such a way. I've tried making it == True but still got nothing. I've also tried using it in try except loops but essentially i dont know what it returns so i cant use it properly.

if WebDriverWait(driver, 50).until(EC.invisibility_of_element_located((By.CLASS_NAME, "NXVPg Szr5J coreSpriteLock "))) == True:
            print("Now its loaded")
        else:
            print("Nope not loaded")

When using it as above, with or without the == True it straight away prints the response of ("Now its loaded") Even if the page hasnt actually changed. However when used like this:

WebDriverWait(driver, 50).until(EC.invisibility_of_element_located((By.CLASS_NAME, "NXVPg Szr5J coreSpriteLock ")))
print("Now its loaded")

It does actually wait and works properly, only problem is i cant use an else to show it hasnt loaded, any help would be greatly appreciated!

1 Answers1

0

WebDriverWait will wait for a maximum of x seconds until the condition is met. If the condition is not met it will throw a TimeoutException. In other words, the if block will never reach the else branch if the condition fails.

Go for a try-except structure:

from selenium.common import exceptions as SE

try:
    WebDriverWait(driver, 10).until(EC.invisibility_of_element_located((*<By relevant identification method here>*)))
    print("Now its loaded")
except SE.TimeoutException:
    print("Nope not loaded")

Note By.CLASS_NAME is not the right one to use as you have multiple class names ("NXVPg Szr5J coreSpriteLock "). An example of a similar issue here.

Use either By.CSS_SELECTOR or By.XPATH instead:

By.CSS_SELECTOR, ".NXVPg.Szr5J.coreSpriteLock "
#or
By.XPATH, "//*[@class='NXVPg Szr5J coreSpriteLock ']"
0buz
  • 3,443
  • 2
  • 8
  • 29
  • Thanks for the clear-up: After testing and debugging more, i found this out too! Question: why shouldn't i use class_name because there is only one class with the name "NXVPg Szr5J coreSpriteLock " when i checked. –  Jun 12 '20 at 14:06
  • A single class name cannot contain spaces. So what you see there are several class names. `.find_element_by_class_name()` or EC `By.CLASS_NAME` matches on single class name. Here's [another example](https://stackoverflow.com/questions/37771604/selenium-compound-class-names-not-permitted) on handling this type of situation. – 0buz Jun 12 '20 at 14:26
  • Ahhh i never knew this, cool thanks so much! Appreciated greatly! –  Jun 12 '20 at 14:35