1

I have something like this

el = WebDriverWait(browser, 10).until(
    EC.presence_of_all_elements_located((By.CSS_SELECTOR, "till-cap"))
)

The problem with the above code is that it does not wait for all the element, it returns 5 instead of 12 elements, sometimes the elements could be more or less, I resolved this by using time.sleep(15) in python, to wait for 15 seconds. But I feel this is not the best way to resolve this. Thank you.

3
  • By using time.sleep(15), you get all of the desired elements? Is there a reason you do not want to use this method? If so, please update your question with why Commented Dec 27, 2023 at 15:42
  • Yes, I do, But I feel there are better ways to do this. Thank you Commented Dec 27, 2023 at 15:47
  • if the DOM is still populating, a Stale Element Exception will be thrown when calling a method on one of the elements. You can catch that and re-get the array if caught. I functionize and re-call function if caught... here's a method using time and while loop: stackoverflow.com/questions/66820416/… You can adjust accordingly. Commented Dec 27, 2023 at 18:06

1 Answer 1

1

Although this functionality is not a native function in Selenium, you can implement a lambda function to verify how many elements are present before moving on:

WebDriverWait(browser,10).until(lambda method: len(EC.presence_of_all_elements_located(By.CSS_SELECTOR, "till-cap")) == 12)

Java has Selenium-native functionality for this exact use case, but in Python we must improvise with the lambda method. To avoid a lambda, you could place your time.sleep() after the WebDriverWait function, as the rest of the elements often populate shortly after the first element:

el = WebDriverWait(browser, 10).until(
    EC.presence_of_all_elements_located((By.CSS_SELECTOR, "till-cap"))
)
time.sleep(2)

This could allow you to decrease the time required in time.sleep(), but you will likely have to test a few times to see the minimum time required.

Sign up to request clarification or add additional context in comments.

5 Comments

Using this approach will only check if the elements returned == 12, if elements is more or less, this will fail
You can adjust "==12" to be whatever suits you. Do you want it greater than or equal to 12? okay, use ">= 12" . If you're unsure how many elements there will be, then the "sleep()" method will be best.
Yes, I am not sure of exactly how many elements will be returned
Okay, then placing sleep after your WebDriverWait function sounds like the best solution.
Of course. Cheers, Habib!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.