Blaszard
Blaszard

Reputation: 32005

How to wait for multiple conditions on invisibility_of_element_located using Selenium through Python

I want to wait for the element to disappear on Selenium, but at the same time I must ensure that all the elements are gone. Right now, it is something like this:

element = WebDriverWait(driver, 30).until(
    expected_conditions.element_to_be_clickable((By.XPATH, xpath))
)
is_clickable = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0]))
)
is_clickable_2 = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[1]))
)

if is_clickable and is_clickable_2:
    element.click()

And there are more than two elements on the layovers list, which store xpaths as str.

In this case, can I make all of them into a single function that checks the invisibility of the elements, instead of repeating them? (I mean, make the WebDriverWait takes only one call, and not define another wrapper function.)

Upvotes: 3

Views: 8050

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193388

until_not()

The until_not(method, message='') method from WebDriverWait class calls the method provided with the driver as an argument until the return value is False.


This usecase

As your usecase is to wait for multiple conditions on invisibility_of_element_located() through you can club up both the expected_conditions:

  • WebDriverWait(driver, 30).until(expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0])))
  • WebDriverWait(driver, 30).until(expected_conditions.invisibility_of_element_located((By.XPATH, layovers[1])))

within a single expression using until_not() method through a lambda expression as follows:

WebDriverWait(driver,15).until_not(lambda driver: driver.find_element(By.XPATH,layovers[0]) and driver.find_element(By.XPATH,layovers[1]))

Outro

You can find a couple of similar relevant discussions in:

Upvotes: 3

cruisepandey
cruisepandey

Reputation: 29382

First thing first :

the moment you write WebDriverWait(driver, 30), an object of web driver wait (Explicit wait) will be created.

Instead you can do something like this :

wait = WebDriverWait(driver,10) 

and you can use the reference variable wait as many times as you want in the same class.

You can create a method which will take webdriverwait reference and along with that you can pass xpath or locator as per your requirement.

def my_method(wait, xpath):
wait.until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0]))

Hope this helps.

Upvotes: 0

Related Questions