MikeCode
MikeCode

Reputation: 91

Break For loop after element found

I am searching and selecting a specific user in a popup window. However, when the user is selected, window closes automatically and that break the for loop and give me an error. Looking for a way to break out of both For loop after a user is selected. Any help will be appreciated.

Here is my code

table_id = driver.find_element_by_xpath("//table[@class='list']")
rows = table_id.find_elements(By.TAG_NAME, "tr")
for row in rows:
    for col in row.find_elements(By.TAG_NAME, "th"):
        if col.text.startswith("UserTest") :
            col.click()
            break

After UserTest selected popup window closes by default. Although, For loop is still running and trying to run next iteration and that throws an error

NoSuchWindowException: Message: no such window: window was already closed

Upvotes: 0

Views: 1768

Answers (2)

Sers
Sers

Reputation: 12255

Your break exiting nearest loop, and there's one more parent. Most important, no need to use loops to get element by text. You can use xpath below to click on table header with UserTest text.

driver.find_element_by_xpath("//table[@class='list']//th[starts-with(.,'UserTest')]").click()

Upvotes: 2

aiyan
aiyan

Reputation: 426

What your break is currently doing is merely exiting the inner for loop, not the outer one.

So what you can do is wrap your entire iteration code in a function and use return to exit the whole function.

# <-- snip -->
def loop(rows):
    for row in rows:
        for col in row.find_elements(By.TAG_NAME, "th"):
            if col.text.startswith("UserTest"):
                col.click()
                return
# <-- snip -->

Upvotes: 4

Related Questions