Selenium通过window_handles获取当前窗口句柄,进行页面元素操作
切换回原窗口句柄,进行元素操作
代码如下:(python版)
__author__ = 'liuke'import unittest,time,refrom selenium import webdriverclass 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("kw").send_keys("流柯") driver.find_element_by_id("su").click() driver.find_element_by_partial_link_text("www.cnblogs.com/liu-ke/ ").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_id("blog_nav_sitehome").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("12306") driver.find_element_by_id("su").click() time.sleep(10)def tearDown(self): self.driver.quit()#passif __name__ == "__main__": unittest.main()
以上。
注意driver与新窗口的绑定。