zoukankan      html  css  js  c++  java
  • Selenium-获取当前窗口句柄与切换回原窗口句柄

    转自: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()

    在Python 2.7 使用谷歌浏览器,输出的句柄结果为:

    CDwindow-6A91CFA2-F107-47FB-9CEE-06E6E4015FE0
    CDwindow-C22573F7-EAFA-41FF-911B-B63AA2D9246F
    CDwindow-6A91CFA2-F107-47FB-9CEE-06E6E4015FE0

     

    附:

    也可以用driver.switch_to_window(driver.window_handles[-1]),来获取当前打开的窗口

    ----夫英雄者,胸怀大志,腹有良谋,有包藏宇宙之机,吞吐天地之志者也。
  • 相关阅读:
    fused multiply and add
    gcc优化选项解析
    gcc的搜索路径,头文件和库
    使用-Wl直接向ld传递参数
    ldd LD_TRACE_LOADED_OBJECTS
    linux下库的使用
    在RedHat 5下安装Oracle 10g详解(转)
    Centos下安装X Window+GNOME Desktop+FreeNX
    oracle exp direct 执行机制
    详解Oracle的unlimited tablespace系统权限
  • 原文地址:https://www.cnblogs.com/eagleking0318/p/6521025.html
Copyright © 2011-2022 走看看