简体   繁体   English

找到元素后中断 For 循环

[英]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.但是,当用户被选中时,窗口会自动关闭,这会中断 for 循环并给我一个错误。 Looking for a way to break out of both For loop after a user is selected.寻找一种在用户被选中后跳出 For 循环的方法。 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. UserTest 选择后弹出窗口默认关闭。 Although, For loop is still running and trying to run next iteration and that throws an error尽管 For 循环仍在运行并尝试运行下一次迭代并引发错误

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

What your break is currently doing is merely exiting the inner for loop, not the outer one.您的break当前所做的只是退出内部for循环,而不是外部循环。

So what you can do is wrap your entire iteration code in a function and use return to exit the whole function.因此,您可以做的是将整个迭代代码包装在一个函数中,并使用return退出整个函数。

# <-- 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 -->

Your break exiting nearest loop , and there's one more parent.您的break退出最近的loop ,并且还有一个父级。 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.您可以使用下面的 xpath 单击带有UserTest文本的表头。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM