zoukankan      html  css  js  c++  java
  • Selenium WebDriver-通过页面标题切换窗口

    selenium webdriver可以通过获取页面标题,再跟据标题去切换浏览器窗口,代码如下:

    #encoding=utf-8
    import unittest
    import time
    import chardet
    from selenium import webdriver
     
    class VisitSogouByIE(unittest.TestCase):
    
        def setUp(self):
            # 启动chrome浏览器
            self.driver = webdriver.Chrome(executable_path = "e:\chromedriver")
    
        def test_operateWindowHandle(self):
            url = "http://www.baidu.com"
            self.driver.get(url)
            # 获取当前窗口句柄
            now_handle = self.driver.current_window_handle
            # 打印当前获取的窗口句柄
            print now_handle
            # 百度搜索输入框中输入“selenium”
            self.driver.find_element_by_id("kw").send_keys("w3cschool")
            # 点击搜索按钮
            self.driver.find_element_by_id("su").click()
            # 导入time包
            import time
            # 等待3秒,以便网页加载完成
            time.sleep(3)
            # 点击w3school在线教育链接
            self.driver.find_element_by_xpath('//div[@id="1"]//a[text()="w3"]').click()
            time.sleep(5)
            # 获取所有窗口句柄
            all_handles = self.driver.window_handles
            # 循环遍历所有新打开的窗口句柄,也就是说不包括主窗口
            for handle in all_handles:            
                self.driver.switch_to.window(handle)
                print type(self.driver.title)
                print self.driver.title
                if self.driver.title == u"w3school 在线教程":
                    # 点击HTML5链接
                    self.driver.find_element_by_link_text('HTML5').click()
                    time.sleep(3)
                if self.driver.title == u"w3cschool_百度搜索":
                   time.sleep(2)
                   self.driver.find_element_by_id("kw").clear()
                   self.driver.find_element_by_id("kw").send_keys(u"光荣之路自动化测试培训")
                   self.driver.find_element_by_id("su").click()
                   time.sleep(5) 
    
        def tearDown(self):
            # 退出IE浏览器
            self.driver.quit()
    
    if __name__ == '__main__':
        unittest.main()
  • 相关阅读:
    暑假学习日记2013/7/20
    java二维码之利用谷歌的zxing生成二维码,解析二维码
    数组去重
    MVC VS2012 Code First 数据库迁移教程
    WIN8 MTK驱动不能安装解决办法
    洛谷 P1943 LocalMaxima_NOI导刊2009提高(1)
    BZOJ 1572 USACO 2009 Open 工作安排
    BZOJ 1724 USACO 2006 Nov. 切割木板
    BZOJ 1666 USACO 2006 Oct. 奶牛的数字游戏
    BZOJ 4094 USACO 2013 Dec. Optimal Milking
  • 原文地址:https://www.cnblogs.com/qingqing-919/p/8709125.html
Copyright © 2011-2022 走看看