使用 python 在 Selenium 中关闭弹出窗口 windows
Closing Popup windows in Selenium using python
我正在尝试关闭弹出窗口 windows,并且处理程序值不固定,每次 运行 时它们都会改变。我想拉出流行标题并使用 for 循环来关闭()弹出窗口,但弹出窗口没有标题。
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get('https://www.naukri.com/')
# driver.maximize_window()
parent = driver.current_window_handle
print(f"This is parent window : {parent}")
uselessWindows = driver.window_handles
print(f"This has the parent window and also the two popup windows : {uselessWindows}")
输出为
This is parent window : CDwindow-196D8EFD5DD167AUTHE8935233FE0140 #String Value
This has the parent window and also the two popup window : ['CDwindow-196D8EFD5DD167AUTHE8935233FE0140', 'CDwindow-9E2058C9AADEWDHUIO4758B2F378AF577', 'CDwindow-94B59B8JGUTJ46578DHKDLNM24658C7C'] #List Value
每次“CDwindow -”后的值每次都改变,我无法使用设置差异-
,因为current_window_handle
在字符串中而window_handles
是在列表中。请帮助我解决关闭弹出窗口的问题。
您必须遍历 window 个句柄列表,并关闭不是父句柄的列表。
driver.get('https://www.naukri.com/')
parent = driver.current_window_handle
uselessWindows = driver.window_handles
for winId in uselessWindows:
if winId != parent:
driver.switch_to.window(winId)
driver.close()
parent = driver.current_window_handle
print(f"This is parent window : {parent}")
uselessWindows = driver.window_handles
print(
f"This has the parent window and also the two popup windows : {uselessWindows}")
driver.switch_to.window(uselessWindows[-1])
driver.close()
driver.switch_to.window(uselessWindows[0])
弹出窗口 window 是您可以使用上述代码的列表中的最后一个元素,您必须切换回父级才能继续执行
我正在尝试关闭弹出窗口 windows,并且处理程序值不固定,每次 运行 时它们都会改变。我想拉出流行标题并使用 for 循环来关闭()弹出窗口,但弹出窗口没有标题。
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get('https://www.naukri.com/')
# driver.maximize_window()
parent = driver.current_window_handle
print(f"This is parent window : {parent}")
uselessWindows = driver.window_handles
print(f"This has the parent window and also the two popup windows : {uselessWindows}")
输出为
This is parent window : CDwindow-196D8EFD5DD167AUTHE8935233FE0140 #String Value
This has the parent window and also the two popup window : ['CDwindow-196D8EFD5DD167AUTHE8935233FE0140', 'CDwindow-9E2058C9AADEWDHUIO4758B2F378AF577', 'CDwindow-94B59B8JGUTJ46578DHKDLNM24658C7C'] #List Value
每次“CDwindow -”后的值每次都改变,我无法使用设置差异-
,因为current_window_handle
在字符串中而window_handles
是在列表中。请帮助我解决关闭弹出窗口的问题。
您必须遍历 window 个句柄列表,并关闭不是父句柄的列表。
driver.get('https://www.naukri.com/')
parent = driver.current_window_handle
uselessWindows = driver.window_handles
for winId in uselessWindows:
if winId != parent:
driver.switch_to.window(winId)
driver.close()
parent = driver.current_window_handle
print(f"This is parent window : {parent}")
uselessWindows = driver.window_handles
print(
f"This has the parent window and also the two popup windows : {uselessWindows}")
driver.switch_to.window(uselessWindows[-1])
driver.close()
driver.switch_to.window(uselessWindows[0])
弹出窗口 window 是您可以使用上述代码的列表中的最后一个元素,您必须切换回父级才能继续执行