Python和Selenium:发生Selenium异常时代码未执行

时间:2019-03-28 08:20:21

标签: python selenium selenium-webdriver

我有一个运行selenium webdriver的Python脚本,该脚本在以下步骤中执行:

1)执行for循环,该循环运行了x次 2)在main for循环中,Selenium Web驱动程序使用xpath查找页面上的按钮 3)对于硒发现的每个按钮,嵌套的for循环单击每个按钮 4)单击按钮后,将打开一个弹出窗口,该窗口会重定向弹出窗口中的随机网站 5)此外,Selenium Webdriver在弹出窗口中找到其他按钮,然后单击按钮,关闭弹出窗口并返回主窗口,以单击主网站上的第二个按钮

此代码在执行时可以正常工作,但是在发生硒异常时会发生此问题。

1)如果弹出窗口有空白页,则发生硒异常,但是为该异常编写的代码未执行 2)如果弹出窗口在超时后由主网站关闭(不是由selenium webdriver关闭),则发生NoSuchWindowException,但在此异常下永远不会执行

我曾尝试通过添加if else条件多次更改代码,但无法解决NoSuchWindowException异常

下面是代码:

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")

每次尝试由主网站关闭弹出窗口时,我都试图通过python代码本身来处理NoSuchWindowException,发生此异常,并且python脚本停止执行下一个for循环:

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

2 个答案:

答案 0 :(得分:0)

两件事:

1)在except中,您使用的是driver.close(),然后尝试将已经关闭的driverdriver.switch_to.window(driver.window_handles[0])一起使用,因此出现错误:

  

selenium.common.exceptions.NoSuchWindowException:消息:没有这样的窗口:目标窗口已关闭   来自未知错误:找不到网页视图

2)您应该再将tryexcept放在一行特定的代码行中,我认为它太宽泛了...

仅出于最佳实践,您不应使用这样的结构化XPath:

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]")

它肯定会破裂。

尝试使用css-selector或更具体的XPath

希望这对您有帮助!

答案 1 :(得分:0)

我要确保在driver.close()之前先切换到关闭窗口。

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