'How can I specify the number of elements that test positive for the locator I'm using?

In Selenium when waiting for an element to load how can I specify the number of elements that test positive for the locator I'm using?

This is my case, I want to check for a div of class 'classA' which contains a text 'text2':

WebDriverWait(driver,3)
    .until(expected_conditions
        .text_to_be_present_in_element(
            (By.CLASS_NAME, 'classA'), 'text2'))

but this is going to time out with however long a wait I set, while the previous element also with 'classA' but with 'text1' is found without issue.

I think Selenium is locating the previous element based on class, than testing if its text ever changes to 'text2'.

I want to find the second element based on class, then test for its text (note that presence_of_all_elements_located will return as soon as it founds a single positive).



Solution 1:[1]

You can achieve this with custom wait condition using lambda. For example, in case you want to wait 3 seconds until number of elements will be equal 2:

WebDriverWait(driver,3)
   .until(lambda method: len(driver.find_elements(By.CLASS_NAME, 'className')) == 2)

Solution 2:[2]

You can not do it with existing built-in methods in Python.
In Java we have expected conditions like

wait.until(ExpectedConditions.numberOfElementsToBe(element, expectedElementsAmount));

and

wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(element,expectedElementsAmount));

but these methods are missing in Python.
You can implement such custom methods by yourself in Python

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Prophet