Selenium 切换到弹出窗口

use*_*901 3 python selenium selenium-webdriver

单击单选按钮时,会打开一个新的弹出窗口,Selenium 无法从新的弹出窗口中找到任何元素。如何将 Selenium 切换到新的弹出窗口,或提取弹出窗口的 URL?

print(driver.current_url)
Run Code Online (Sandbox Code Playgroud)

检索旧选项卡的 URL,而不是弹出窗口的 URL。

print(driver.title)
Run Code Online (Sandbox Code Playgroud)

打印旧选项卡的标题,而不是弹出窗口的标题。

提前致谢。

tbj*_*rch 6

当您打开弹出窗口时,您可能会获得一个额外的窗口句柄,并且需要更改窗口句柄以与弹出窗口交互。这可以在 driverswindow_handles属性中检查,并使用 driversswitch_to_window方法切换到。

# before clicking button to open popup, store the current window handle
main_window = driver.current_window_handle

# click whatever button it is to open popup

# after opening popup, change window handle
for handle in driver.window_handles: 
    if handle != main_window: 
        popup = handle
        driver.switch_to_window(popup)

print(driver.title) # Should now be the popup window
Run Code Online (Sandbox Code Playgroud)

  • 这个答案非常有帮助。 (2认同)