自动化测试(3-4):基本API

  • (1)判断页面元素是否存在
#例子:判断页面元素是否存在(以后可以用在if里面进行判断,根据判断的结果往下进行)
import unittest
import time
from selenium import webdriver
from selenium.webdriver import ActionChains

class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动IE浏览器
        #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
        self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
        
    def isElementPresent(self, by, value):
        # 从selenium.common.exceptions模块导入NoSuchElementException异常类
        from selenium.common.exceptions import NoSuchElementException
        try:
            # by表示用哪种方式进行定位,valaue表示表达式
            element = self.driver.find_element(by=by, value=value)
        except NoSuchElementException as e:
            # 打印异常信息
            print (e)
            # 发生了NoSuchElementException异常,说明页面中未找到该元素,返回False
            return False
        else:
            # 没有发生异常,表示在页面中找到了该元素,返回True
            return True
        
    def test_isElementPresent(self):
        url = "http://www.sogou.com"
        # 访问sogou首页
        self.driver.get(url)
        # 调用上面封装的方法来判断页面元素id属性值为"query"的页面元素是否存在
        res = self.isElementPresent("id", "query")   #也可以写成xpath的方式:res = self.isElementPresent("xpath", "//input[@id='query']")
        time.sleep(2)
        if res is True:
            print (u"所查找的元素存在于页面上!")
        else:
            print (u"页面中未找到所需要的页面元素!")

    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()   
  • (2)隐式等待implicitly_wait()
#例子:隐式等待implicitly_wait(设置的等待时间),在定位元素时分以下两种情况:
#(1)如果定位不到元素会等待几秒(即设置的等待时间,在这个过程中会再去进行定位,如果在这几秒还没有定位到,就会报错)
#(2)如果定位到元素不会等待
#(只要有implicitly_wait(设置的等待时间)这一句话,默认对所有代码中定位元素时进行隐式等待。只要声明了driver就可以声明这一句话)
import unittest
import time
from selenium import webdriver
from selenium.webdriver import ActionChains

class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动IE浏览器
        #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
        self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
        
    def test_implictWait(self):
        # 导入异常类
        from selenium.common.exceptions import NoSuchElementException, TimeoutException
        # 导入堆栈类
        import traceback
        url = "http://www.sogou.com"
        # 访问sogou首页
        self.driver.get(url)
        # 通过driver对象implicitly_wait()方法来设置隐式等待时间,最长等待10秒,如果10秒内返回则继续执行后续脚本
        # 只要声明了driver对象,就可以把这句话声明在drriver对象后面的任何地方
        self.driver.implicitly_wait(10)
        try:
            # 查找sogou首页的搜索输入框页面元素
            searchBox = self.driver.find_element_by_id("query")
            # 在搜索输入框中输入“北京”
            searchBox.send_keys(u"北京")
            # 查找sogou首页搜索按钮页面元素
            click = self.driver.find_element_by_id("stb")
            # 点击搜索按钮
            click.click()
            time.sleep(2)
        except (NoSuchElementException, TimeoutException) as e:
            # 打印异常的堆栈信息
            traceback.print_exc()

    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (3)显示等待until()
#例子:显示等待until()
#作用:判断指定元素的一些特定条件(判断在不在,是不是可点击,是否可用),比隐式等待更灵活(隐式等待只能判断是否存在)
#缺点:每个定位的元素都要写
#例子1:
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
driver.get("http://www.sogou.com")
input_box=driver.find_element_by_id("query")

wait = WebDriverWait(driver, 10, 0.2) 
# 表示在10秒之内,每0.2秒就会判断输入框input_box是否可见,只要显示出来,就在里面输入"北京"
wait.until(EC.visibility_of(input_box))
input_box.send_keys(u"北京")

# 表示在10秒之内,每0.2秒就会判断某个元素是否可点击,只要可点击,找到这个元素,然后点击
wait.until(EC.element_to_be_clickable((By.ID ,"stb")))  
button=driver.find_element_by_id("stb")
button.click()

time.sleep(3)
driver.close()
#例子2:
import unittest
import time
from selenium import webdriver
from selenium.webdriver import ActionChains

class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动IE浏览器
        #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
        self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
        
    def test_explicitWait(self):
        # 导入堆栈类
        import traceback
        # 导入By类
        from selenium.webdriver.common.by import By
        # 导入显示等待类
        from selenium.webdriver.support.ui import WebDriverWait
        # 导入期望场景类
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.common.exceptions import TimeoutException, NoSuchElementException
        url = "http://127.0.0.1/test_explicity_wait.html"
        # 访问自动以测试网页
        self.driver.get(url)
        try:
            wait = WebDriverWait(self.driver, 10, 0.2)
            wait.until(EC.title_is(u"你喜欢的水果"))           #表示在10秒之内,每0.2秒就会判断标题是否是"你喜欢的水果",如果是,继续往下进行
            print (u"网页标题是'你喜欢的水果'")
            # 等待10秒,直到要找的按钮出现,不写间隔时间默认就是0.2,x=self.driver
            element = WebDriverWait(self.driver, 10).until(lambda x:x.find_element_by_xpath("//input[@value='Display alert box']"))
            element.click()
            # 等待alert框出现
            alert = wait.until(EC.alert_is_present())          #判断alert框是否出现
            print("alert=%s" %alert)
            # 打印alert框体消息
            print (alert.text)
            # 点击alert的确认
            alert.accept()
            # 获取id属性值为“peach”的页面元素
            peach = self.driver.find_element_by_id("peach")
            # 判断id属性值为“peach”的页面元素是否能被选中
            peachElement = wait.until(EC.element_to_be_selected(peach))   
            print("peachElement=%s" %peachElement)
            # 判断复选框是否可见并且能被点击
            checkbox = wait.until(EC.element_to_be_clickable((By.ID, 'check')))
            print("checkbox=%s" %checkbox)
            print (u"复选框可见并且能被点击")
        except TimeoutException as e:
            # 捕获TimeoutException异常
            print (traceback.print_exc())
        except NoSuchElementException as e:
            # 捕获NoSuchElementException异常
            print (traceback.print_exc())
        except Exception as e:
            # 捕获其他异常
            print (traceback.print_exc())

    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (4)使用Title属性识别和操作新弹出的浏览器窗口
#例子:使用Title属性识别和操作新弹出的浏览器窗口
import unittest
import time
from selenium import webdriver
from selenium.webdriver import ActionChains

class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动chrome浏览器
        #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
        self.driver = webdriver.Chrome(executable_path="E:\\chromedriver")
        
    def test_identifyPopUpWindowByTitle(self):
        # 导入多个异常类型
        from selenium.common.exceptions import NoSuchWindowException, TimeoutException
        # 导入期望场景类
        from selenium.webdriver.support import expected_conditions as EC
        # 导入By类
        from selenium.webdriver.common.by import By
        # 导入WebDriverWait类
        from selenium.webdriver.support.ui import WebDriverWait
        # 导入堆栈类
        import traceback
        url = "http://127.0.0.1/test_popup_window.html"
        # 访问自动以测试网页
        self.driver.get(url)
        time.sleep(3)
        # 显示等待找到页面上链接文字为“sogou 搜索”的链接元素,找到后点击它
        WebDriverWait(self.driver, 10, 0.2).until(EC.element_to_be_clickable((By.LINK_TEXT, 'sogou 搜索'))).click()
        # 获取当前所有打开的浏览器窗口句柄
        all_handles = self.driver.window_handles
        # 打印当前浏览器窗口句柄
        print (self.driver.current_window_handle)
        # 打印打开的浏览器窗口的个数
        print (len(all_handles))
        # 等待2秒,以便更好查看效果
        time.sleep(5)
        # 如果存储浏览器窗口句柄的容器不为空,再遍历all_handles中所有的浏览器句柄
        if len(all_handles) > 0:
            try:
                for windowHandle in all_handles:
                    # 切换窗口
                    self.driver.switch_to.window(windowHandle)
                    print (self.driver.title)
                    # 判断当前浏览器窗口的title属性是否等于“搜狗搜索引擎 - 上网从搜狗开始”
                    if self.driver.title == u"搜狗搜索引擎 - 上网从搜狗开始":
                        # 显示等待页面搜索输入框加载完成,然后输入“sogou 首页的浏览器窗口被找到”
                        WebDriverWait(self.driver, 10, 0.2).until(lambda x: x.find_element_by_id("query")).send_keys(u"sogou 首页的浏览器窗口被找到")
                        time.sleep(3)
            except NoSuchWindowException as e:
                # 捕获NoSuchWindowException异常
                print (traceback.print_exc())
            except TimeoutException as e:
                # 捕获TimeoutException异常
                print (traceback.print_exc())
        # 将浏览器窗口切换回默认窗口
        self.driver.switch_to.window(all_handles[0])
        time.sleep(3)
        print (self.driver.title)
        # 断言当前浏览器窗口的title属性是“你喜欢的水果”
        self.assertEqual(self.driver.title, u"你喜欢的水果")

    def tearDown(self):
        # 退出chrome浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main() 
  • (5)操作iframe中的页面元素(iframe使用的比较多,frame现在基本不用)
 #例子:操作iframe中的页面元素(嵌入多层,退出退到最外层)
 #左边的frame(可以拖动,现在基本不用)里面有嵌入了一个iframe(iframe固定大小,不能拖动,现在都是用iframe)
import unittest
import time
from selenium import webdriver
from selenium.webdriver import ActionChains

class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动IE浏览器
        #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
        self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
        
    def test_HandleIFrame(self):
        url = "http://127.0.0.1/frameset.html"   
        # 访问自动以测试网页
        self.driver.get(url)
        # 改变操作区域,切换进入页面上第一个frame,也就是左边的frame
        self.driver.switch_to.frame(0)
        # 断言页面是否存在“这是左侧 frame 页面上的文字”关键字串,以判断是否成功切换进frame页面
        assert u"这是左侧 frame 页面上的文字" in self.driver.page_source
        
        # 改变操作区域,切换进入id为“showIfame”的iframe页面(即嵌入的iframe页面里面)
        self.driver.switch_to.frame(self.driver.find_element_by_xpath("//iframe"))
        # 断言页面是否存在“这是iframe页面上的文字”这样的关键字串,以便判断是否成功切换进iframe页面
        assert u"这是iframe页面上的文字" in self.driver.page_source
    
        # 返回到frameset页面(最初的位置)
        self.driver.switch_to.default_content()
        # 断言页面的title值是否为“frameset 页面”
        assert u"frameset 页面" == self.driver.title
    
    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (6)操作Alert弹框中的确定和取消(很少用)
#例子:操作Alert弹框中的确定和取消(很少用)
import unittest
import time
from selenium import webdriver
from selenium.webdriver import ActionChains

class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动IE浏览器
        #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
        self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
        
    def test_Handleconfirm(self):
        from selenium.common.exceptions import NoAlertPresentException
        import time
        url = "http://127.0.0.1/test_confirm.html"
        # 访问自动以测试网页
        self.driver.get(url)
        # 通过id属性值查找页面上的按钮元素
        button = self.driver.find_element_by_id("button")
        # 单击按钮元素,则会弹出一个confirm提示框,上面显示"这是一个 confirm 弹出框"、"确定"和"取消"按钮
        button.click()
        time.sleep(2)
        try:
            # 较高版本的selenium推荐使用driver.switch_to.alert方法代替
            # driver.switch_to_alert()方法来获取alert对象
            alert = self.driver.switch_to.alert
            time.sleep(2)
            # 使用alert.text属性获取confirm框中的内容,并断言文字内容是否是"这是一个 confirm 弹出框"
            self.assertAlmostEqual(alert.text, u"这是一个 confirm 弹出框")
            # 调用alert对象的accept()方法,模拟鼠标单击confirm弹窗上的"确定"按钮,以便关闭confirm窗
            # alert.accept()
            # 模拟单击confirm框上的"取消"按钮
            alert.dismiss()
        except NoAlertPresentException as e:
            # 如果confirm框未弹出显示在页面上,则会抛出NoAlertPresentException的异常
            self.fail("尝试操作的confirm框未被找到")
            print (e)

    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (7)操作浏览器的cookie(很少测)
#例子:操作浏览器的cookie(很少测)
import unittest
import time
from selenium import webdriver
from selenium.webdriver import ActionChains

class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动IE浏览器
        #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
        self.driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
        
    def test_Cookie(self):
        url = "http://www.baidu.com"
        # 访问百度首页
        self.driver.get(url)
        time.sleep(2)
        # 得到当前页面下所有的Cookies,并输出它们所在域、name、value、有效期和路径
        cookies = self.driver.get_cookies()
        print("百度首页所有的Cookies如下:")
        for cookie in cookies:
            print (cookie)
            
        print("*"*100)       
        # 根据Cookie的name值获取该条Cookie信息,获取name值为'SUV'的Cookie信息
        ck = self.driver.get_cookie("SUV")
        print ("name值为'SUV'的Cookie信息:",ck)
        
        print("*"*100)        
        # 删除cookie有2种方法
        # 第一种:通过Cookie的name属性,删除name值为“ABTEST”的Cookie信息
        print ("name值为“ABTEST”的Cookie信息之后显示:",self.driver.delete_cookie("ABTEST"))
        print("*"*100)
     
        # 第二种:一次性删除全部Cookie信息
        self.driver.delete_all_cookies()
        # 删除全部Cookie后,再次查看Cookies,确认是否已被全部删除
        cookies = self.driver.get_cookies()
        print ("删除全部Cookie后,再次查看Cookies:",cookies)
        print("*"*100)
        
        # 添加自定义Cookie信息
        self.driver.add_cookie({"name": "gloryroadTrain", 'value': '1479697159269020'})
        # 查看添加的Cookie信息
        cookie = self.driver.get_cookie("gloryroadTrain")
        print ("添加自定义Cookie信息:",cookie)

    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值