Transferred from: http://blog.csdn.net/hhabc123456789/article/details/21862139
#-*-coding:cp936-*-
__author__ = ' Administrator '
Import Unittest,time,re
From selenium import Webdriver
Class Untitled (UnitTest. TestCase):
def setUp (self):
Self.driver = Webdriver. Chrome ()
Self.driver.implicitly_wait (10)
Self.url = "Http://www.baidu.com"
def test_untitled (self):
Driver = Self.driver
Driver.get (Self.url)
Now_handle = Driver.current_window_handle #获取当前窗口句柄
Print Now_handle #输出当前获取的窗口句柄
driver.find_element_by_id ("Kw1"). Send_keys ("Selenium")
driver.find_element_by_id ("SU1"). Click ()
Driver.find_element_by_xpath ("//*[@id = ' 1 ']/h3/a[1]"). Click ()
Time.sleep (2)
All_handles = Driver.window_handles #获取所有窗口句柄
For handle in All_handles:
If handle! = Now_handle:
Print Handle #输出待选择的窗口句柄
Driver.switch_to_window (handle)
Driver.find_element_by_xpath ("//*[@id = ' menu_projects ']/a"). Click ()
Time.sleep (5)
Driver.close () #关闭当前窗口
Time.sleep (3)
Print Now_handle #输出主窗口句柄
Driver.switch_to_window (Now_handle) #返回主窗口
Time.sleep (2)
driver.find_element_by_id ("kw"). Clear ()
driver.find_element_by_id ("kw"). Send_keys ("abc")
driver.find_element_by_id ("su"). Click ()
Time.sleep (10)
def tearDown (self):
Self.driver.quit ()
#pass
if __name__ = = "__main__":
Unittest.main ()
In Python 2.7 using Google Chrome, the output handle results are:
Cdwindow-6a91cfa2-f107-47fb-9cee-06e6e4015fe0
cdwindow-c22573f7-eafa-41ff-911b-b63aa2d9246f
Cdwindow-6a91cfa2-f107-47fb-9cee-06e6e4015fe0
Report:
You can also use Driver.switch_to_window (Driver.window_handles[-1]) to get the currently open window
Use Selenium+python; Click a button on page A to jump to page B, page A is not closed, the browser opens a B, the toggle window locates the element of page B