【问题标题】:Closing Popup windows in Selenium using python使用 python 关闭 Selenium 中的弹出窗口
【发布时间】:2021-02-01 05:56:19
【问题描述】:

我正在尝试关闭弹出窗口,并且处理程序的值不是固定的,每次再次运行时它们都会改变。我想拉弹出标题并使用 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 在列表中。请帮助我找到关闭弹出窗口的解决方案。

【问题讨论】:

  • 基本上它是 PDHide 和 Buabans 的组合解决方案,即删除无用的窗口并切换回父级。
  • @ArundeepChohan 非常感谢,_/_

标签: python-3.x selenium selenium-webdriver selenium-chromedriver popupwindow


【解决方案1】:

您必须遍历窗口句柄列表,并关闭不是父级的。

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

【讨论】:

  • 您好 buaban,当代码被执行时,当代码试图继续进行时,我收到此错误selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed 执行上述代码后,代码显示该错误。
  • 这是我在任何地方找到的最干净的关闭弹出代码!
【解决方案2】:
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])

弹出的窗口是列表中的最后一个元素,你可以使用上面的代码,你必须切换回父级才能继续执行

【讨论】:

  • 好的,非常感谢 pdhide,我可以问一下吗?
  • 当然请询问
  • 再次感谢 pdhide,在这种情况下,我们有固定数量的弹出窗口,所以我们使用 -1,如果有这么多弹出窗口怎么办(这将在我们运行网站后确定),所以在这个如果我们无法预先判断有多少弹出窗口,那么可以做什么,我们只想单独使用第一个以及如何关闭其他弹出窗口,
  • @Gab0623 您可以使用 buabans 回答遍历 windows 句柄并在 for 循环外使用 driver.switch_to.window(parent)
  • 谢谢你隐藏的解释
猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
  • 2020-06-22
  • 1970-01-01
相关资源
最近更新 更多