Javed Shaik
Javed Shaik

Reputation: 29

Python & Selenium: Code not executing while Selenium exception occurs

I have a Python script that runs selenium webdriver that executes in the following steps:

1) Execute a for loop that runs for x number of times 2) Within the main for loop, selenium web driver finds buttons on the page using xpath 3) For each button found by selenium, the nested for loop clicks each button 4) Once a button is clicked, a popup window opens, that redirects random websites within the popup 5) Further, the selenium webdriver finds other buttons within the popup and clicks the button, closes the popup and returns to main window to click the second button on the main website

This code works fine while executing, but the issue occurs while selenium exceptions happen.

1) If the popup window has blank page, then selenium exception occurs, but the code written for that exception is not executing 2) If the popup closes by the main website after timeout(not closed by selenium webdriver), then NoSuchWindowException occours, but the under this exception never executes

I have tried changing the code several times by adding if else condition, but not able to resolve NoSuchWindowException exceptio

Below is the code:

for _ in range(100):
    print("main loop pass")

    fb_buttons = driver.find_elements_by_xpath('//a[contains(@class,"pages_button profile_view")]')

    for button in fb_buttons:
        try:
            time.sleep(10)
            button.click()
            driver.implicitly_wait(5)
            driver.switch_to.window(driver.window_handles[1])
            driver.execute_script("window.scrollTo(0, 2500)")
            print("wiindow scrolled")

            like_right = driver.find_elements_by_xpath(
                "/html[1]/body[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[3]/div[1]/div[1]")
            like_left = driver.find_elements_by_xpath(
                "/html/body/div[1]/div/div[2]/div/div[1]/div[1]/div[2]/div/div[2]/table/tbody/tr/td[1]/a[1]")

            while like_right:
                for right in like_right:
                    right.click()
                break
            while like_left:
                for left in like_left:
                    left.click()
                break
            while like_post:
                for like in like_post:
                    like.click()
                break
            time.sleep(5)
            driver.close()
            driver.implicitly_wait(5)
            driver.switch_to.window(driver.window_handles[0])
            print("clicks executed successfully")
            continue

        except StaleElementReferenceException as e:


            driver.close()
            driver.switch_to.window(driver.window_handles[0])
            popunder = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[3]/p[2]/a")
            if popunder is True:
                popunder.click()
                driver.implicitly_wait(5)
            else:
                continue
            print("exception occured-element is not attached to the page document")

        except ElementNotVisibleException as e:

            driver.close()
            driver.switch_to.window(driver.window_handles[0])
            popunder = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[3]/p[2]/a")
            if popunder is True:
                popunder.click()
                driver.implicitly_wait(5)
            else:
                continue
            print("Exception occured - ElementNotVisibleException")

        except WebDriverException as e:

            driver.close()
            driver.switch_to.window(driver.window_handles[0])
            popunder = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[3]/p[2]/a")
            if popunder is True:
                popunder.click()
                driver.implicitly_wait(5)
            else:
                continue
            print("Exception occured - WebDriverException")

        except NoSuchWindowException as e:
            driver.switch_to.window(driver.window_handles[0])
            popunder = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[3]/p[2]/a")
            if popunder is True:
                popunder.click()
                driver.implicitly_wait(5)
            else:
                continue
            print("Exception - NoSuchWindowException - Switched to main window")

    else:
        time.sleep(5)
        refresh.click()
        print("refreshed")

I am trying to handle the NoSuchWindowException by the python code itself as everytime the popup window closes by main website, this exception occurs and python script stops to execute the next for loop:

File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
from unknown error: web view not found
  (Session info: chrome=73.0.3683.86)
  (Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Windows NT 6.1.7601 SP1 x86_64)


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/javed/PycharmProjects/clicks/test/fb-click-perfect-working.py", line 98, in <module>
    driver.close()
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 688, in close
    self.execute(Command.CLOSE)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
from unknown error: web view not found
  (Session info: chrome=73.0.3683.86)
  (Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Windows NT 6.1.7601 SP1 x86_64)


Process finished with exit code 1

Upvotes: 0

Views: 1067

Answers (2)

supputuri
supputuri

Reputation: 14135

I would make sure to switch to the closing window first, before driver.close().

driver.switch_to.window(driver.window_handles[1]) 
driver.close() 
driver.switch_to.window(driver.window_handles[0])

Upvotes: 0

Moshe Slavin
Moshe Slavin

Reputation: 5204

Two things:

1) In the except you are using driver.close() then you try to use the already closed driver with driver.switch_to.window(driver.window_handles[0]) hence the error:

selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed from unknown error: web view not found

2) You should put the try and except one more specific lines of code it's too broad in my opinion...

Just for best practice, you shouldn't use such structured XPath's:

driver.find_elements_by_xpath("/html[1]/body[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[3]/div[1]/div[1]")

It's bound to break.

Try using css-selector or a more spcific XPath.

Hope this helps you!

Upvotes: 0

Related Questions