How to wait for the for loop to finish before next statement in Python (and Selenium)?

Viewed 190

I have a list of 10 elements. When I find a match in the list I want to click that element. If no element matches I want to go to the "next page". (It is actually the same page but new async list elements is loaded in the list. Both lists has the same xpath.) Then I want to search the new page and click a element if it matches. Here is the code:

for xpath in list: # loop through elements
    element = WebDriverWait(driver, 40).until(EC.presence_of_all_elements_located((By.XPATH, xpath)))
    element = driver.find_element_by_xpath(xpath) # element fresh each time! no staleness here
    match = re.search(patternForFindingListItem, element.text) #if match then click on the element/item
    if match:
        element.click()
        break
    
if match == None: #want to go to next 10 items (notes) on "next page" (it is the same page but new loaded data via JavaScript) via next-button to see if there is a match there
    elementButton = driver.find_element_by_xpath(xpathNextButton)
    elementButton.click()

The problem is that it gets to the "next page" before the for loop is finished on the "first page". How can we wait for the loop to finish before going to the next page?

1 Answers

There are several possible problems here:

  1. WebDriverWait(driver, 40).until(EC.presence_of_all_elements_located((By.XPATH, xpath))) will not wait untill all the elements matching xpath are presente. It will return once at least one match found.
  2. element = driver.find_element_by_xpath(xpath) according to the previous code line I guess you are trying to get the list of elements here, not a single element. If so you should use find_elements_by_xpath here, so it will be elements = driver.find_elements_by_xpath(xpath)
  3. It's unclear what are you doing here: re.search(patternForFindingListItem, element.text)...
Related