python - 如果我尝试在 python 中关闭当前窗口,则 Windows 处理关闭整个浏览器
问题描述
我目前正在使用 Windows 处理在新窗口中打开地图方向,打开后我将关闭子窗口,该窗口已打开并在代码中进行重新制作工作。但它正在关闭整个浏览器,同时调试它是工作正常,但在运行代码时,我收到错误,
错误 -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()
我在哪里犯了我不知道的错误。请帮我解决。
解决方案
尝试使用此代码关闭新窗口并切换回主窗口
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)
推荐阅读
- mediawiki - 访问语义媒体维基中同一子对象中的其他属性
- qt - QMLProfiler 中的 QML Listview 报告两次委托创建
- javascript - 我怎样才能删除一些注入脚本
- netlogo - 删除netlogo列表中链接的反面
- join - Presto 多表连接和广播连接分布
- python - 当代码仍然有效时,列表索引超出范围?
- google-sheets - 我如何知道已回答的问题来自该部分以及如何计算它们
- java - 在 jUnit 中使用时间
- firebase - 如果我使用 Firestore 作为后端,我的 Flutter App 是否应该实例化一个新对象?
- android-fragments - Android kotlin 片段中的 findViewById