如何在 Selenium for Python 中切换到新窗口? [英] How to switch to new window in Selenium for Python?

查看:63
本文介绍了如何在 Selenium for Python 中切换到新窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 进行 selenium 自动化项目.

I am working on selenium automation project using Python.

我面临一个问题,即处理多个浏览器窗口.

I am facing an issue, which is handling multiple browser windows.

场景如下.当我单击主页上的链接时,会打开一个新窗口.在新打开的窗口中,我无法执行任何操作,因为焦点仍在主页 web 驱动程序上.

Scenario is as follows. When I click a link on the home page, a new window opens. In the newly opened window I cannot perform any actions, because the focus is still on the home page web driver.

谁能告诉我如何将焦点从背景窗口更改为新打开的窗口?

Can anybody show me how to change focus from the background window to the newly opened window?

一个可能的解决方案是driver.switch_to.window(),但它需要窗口的名称.如何找出窗口的名称?如果这是一种错误的方式来执行此操作,有人可以提供一些代码示例来执行此操作吗?

A possible solution is driver.switch_to.window(), but it requires the window's name. How to find out the window's name? If this is a wrong way to do this, can anybody give some code examples to perform this action?

推荐答案

您可以使用window_handlesswitch_to_window 方法来实现.

You can do it by using window_handles and switch_to_window method.

点击链接前先将窗口句柄存储为

Before clicking the link first store the window handle as

window_before = driver.window_handles[0]

点击链接后将新打开的窗口的窗口句柄存储为

after clicking the link store the window handle of newly opened window as

window_after = driver.window_handles[1]

然后执行切换到窗口方法移动到新打开的窗口

then execute the switch to window method to move to newly opened window

driver.switch_to_window(window_after)

同样,您可以在旧窗口和新窗口之间切换.以下是代码示例

and similarly you can switch between old and new window. Following is the code example

import unittest
from selenium import webdriver

class GoogleOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_google_search_page(self):
        driver = self.driver
        driver.get("http://www.cdot.in")
        window_before = driver.window_handles[0]
        print window_before
        driver.find_element_by_xpath("//a[@href='http://www.cdot.in/home.htm']").click()
        window_after = driver.window_handles[1]
        driver.switch_to_window(window_after)
        print window_after
        driver.find_element_by_link_text("ATM").click()
        driver.switch_to_window(window_before)

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

这篇关于如何在 Selenium for Python 中切换到新窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆