Windows处理会关闭整个浏览器(如果我尝试关闭python中的当前窗口) [英] Windows Handling Closes the whole browser if i try to close the current window in python

查看:312
本文介绍了Windows处理会关闭整个浏览器(如果我尝试关闭python中的当前窗口)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在使用Windows处理在新窗口中打开地图方向,然后在打开后我将关闭子窗口,该子窗口将打开并在代码中进行重命名工作,但它将关闭整个浏览器,而调试它可以正常工作,但是在运行代码时,正在获取错误,

Am currently using windows handling for opening the map direction in the new window and after it opens i will be closing the child window, which is opened and do the remaming work in the code.But it is closing the whole browser, while debugging it is working correctly , but while running the code, am Getting the error as,

错误-selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed

我已经附加了代码,

   ##Clicking on The Map Image
            self.driver.find_element_by_xpath("/html[1]/body[1]/div[1]/div[2]/div[1]/section[1]/div[1]/div[1]/div[2]/div[1]/a[1]/img[1]").click()
            ##Setting up an Window Handle to get the size.
            handels =self.driver.window_handles
            size = len(handels)
            """
            The Below For Loop, We are using For Handling The Mutilple Windows,
            Which are opened in the Browser.
            """

            for length in range(size):
                driver.switch_to.window(handels[length])
                print(self.driver.title)
                time.sleep(3)
                if length == 1:
                    driver.close()

我做过错误的地方不知道.请把我整理一下.

Where i have done the error i dunno. please sort me out.

推荐答案

尝试使用此代码关闭新窗口并切换回主窗口

Try this code to close new window and switch back to main window

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Get current window
current = self.driver.current_window_handle
# Get current windows
handles = self.driver.window_handles
# Click button. Consider to use more reliable relative XPath instead of this absolute XPath
self.driver.find_element_by_xpath("/html[1]/body[1]/div[1]/div[2]/div[1]/section[1]/div[1]/div[1]/div[2]/div[1]/a[1]/img[1]").click()
# Wait for new window
WebDriverWait(self.driver, 10).until(EC.new_window_is_opened(handles))
# Switch to new window
self.driver.switch_to.window([w for w in self.driver.window_handles if w != current][0])
# Close new window
self.driver.close()
# Switch back to main window
self.driver.switch_to.window(current)

这篇关于Windows处理会关闭整个浏览器(如果我尝试关闭python中的当前窗口)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆