'Why For loop stop when When the case is except?

for loop stop In case of except When using the line : page.close()

from selenium import webdriver
page = webdriver.Chrome("chromedriver")
page.maximize_window()
def test():
    for i in range(10):
        page.execute_script("window.open()")
        page.switch_to.window(page.window_handles[i + 1])
        page.get(f"https://haraj.com.sa/119174396{i}")
        try:
            Object = page.find_element_by_class_name("contact")
            Object.click()
        except:
            page.close()
            print("Not find element ")
test()

If the find element ("contact") click on it, And the page stays open in Browser Tab If the element ("contact") is not find, the page will be closed And for loop continues If commented #page.close() the for loop will continue And the page that I want to close will stays open in Browser Tab and print("Not find element ") function will be executed Are there other ways to close the page that does not contain element ("contact") and continue for loop?



Solution 1:[1]

Main problem in your code is you are closing browser and then you want to locate element so it will generate error.

There are two solution below

Solution 1:

from selenium import webdriver
page = webdriver.Chrome("chromedriver")
page.maximize_window()
def test():
    for i in range(10):
        page.execute_script("window.open()")
        page.switch_to.window(page.window_handles[i + 1])
        page.get(f"https://haraj.com.sa/119174396{i}")
        try:
            Object = page.find_element_by_class_name("contact")
            Object.click()
        except:
            page.close()
            print("Not find element ")
            page = webdriver.Chrome("chromedriver")
            page.maximize_window()
test()

When element('contact') is not find Above code close the browser and reopen browser again and continue execution

Solution 2:

from selenium import webdriver
page = webdriver.Chrome("chromedriver")
page.maximize_window()
def test():
    for i in range(10):
        page.execute_script("window.open()")
        page.switch_to.window(page.window_handles[i + 1])
        page.get(f"https://haraj.com.sa/119174396{i}")
        try:
            Object = page.find_element_by_class_name("contact")
            Object.click()
        except:
            print("Not find element ")
test()

Above code will not close browser so it will remain same as before exception and continue execution

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 Devam Sanghvi