使用Selenium切换到弹出窗口

3
当点击单选按钮时,会打开一个新的弹出窗口,Selenium无法定位新弹出窗口中的任何元素。如何将Selenium切换到新的弹出窗口或提取弹出窗口的URL?
print(driver.current_url)

获取的是旧标签页的URL而不是弹出窗口的URL。

print(driver.title)

打印的是旧标签页的标题而不是弹出窗口的标题。
提前感谢。

你能提供更多细节和示例吗?听起来你需要切换窗口句柄。 - tbjorch
1个回答

6
当你打开弹出窗口时,可能会得到一个额外的窗口句柄,并且需要更改窗口句柄以与弹出窗口进行交互。 可以在驱动程序的window_handles属性中进行检查,并通过使用驱动程序的switch_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

1
我能够通过下面的代码解决这个问题,谢谢。 driver.switch_to.window(driver.window_handles[2]) - user901
2
这个答案非常有帮助。 - Sushen Biswas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接