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

问题描述 投票:0回答:2

我有一个运行selenium webdriver的Python脚本,它按以下步骤执行:

1)执行运行x次的for循环2)在main for循环中,selenium web驱动程序使用xpath找到页面上的按钮3)对于selenium找到的每个按钮,嵌套的for循环单击每个按钮4)一次单击一个按钮,弹出一个弹出窗口,重定向弹出窗口中的随机网站5)此外,selenium webdriver在弹出窗口中找到其他按钮并单击按钮,关闭弹出窗口并返回主窗口单击第二个按钮主要网站

此代码在执行时工作正常,但在发生selenium异常时会出现问题。

1)如果弹出窗口有空白页面,则发生selenium异常,但是为该异常编写的代码没有执行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
python selenium selenium-webdriver
2个回答
0
投票

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

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

0
投票

两件事情:

1)在except你使用driver.close()然后你尝试使用已经关闭的driverdriver.switch_to.window(driver.window_handles[0])因此错误:

selenium.common.exceptions.NoSuchWindowException:消息:没有这样的窗口:目标窗口已经因未知错误而关闭:找不到Web视图

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

它必将打破。

尝试使用qazxsw poi或更具体的qazxsw poi。

希望这对你有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.