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

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

问题描述

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

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 methow 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
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

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天全站免登陆