Webdriver API(11)隐式等待与显示等待

隐式等待
隐式等待是在测试实施时,为查找页面元素或执行命令设置的一个最长等待时间,如果在规定时间内页面元素被找到或命令执行完成,则执行下一步,否则继续等待直到设置的最长等待时间结束。

#encoding=utf-8
from selenium import webdriver
import unittest
class VisitByFirefox(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox(executable_path="f:\\geckodriver")
    def test_implictWait(self):
        from selenium.common.exceptions import NoSuchElementException,TimeoutException
        import traceback
        url="https://www.sogou.com"
        self.driver.get(url)
        self.driver.implicitly_wait(10)
        try:
            searchBox=self.driver.find_element_by_id("query")
            searchBox.send_keys("光荣之路自动化测试")
            click=self.driver.find_element_by_id("stb")
            click.click()
        except(NoSuchElementException,TimeoutException) as e:
            traceback.print_exc()
    def tearDown(self):
        self.driver.quit()
if __name__ == '__main__':
        unittest.main()

隐式等待的好处是不用像time.sleep(n)一样死等固定的时间,可以一定程度上提升测试效率。弊端就是加长了测试用例的执行时间
隐式等待只需设置一次,然后在driver整个生命周期起作用
显示等待
更智能的等待方式,节约测试脚本执行时间,推荐使用显示等待来判断页面元素是否存在
使用WebDriverWait类中的方法:until和until_not
timeout:最长显示等待时间,单位为秒
poll_frequency:调用频率,默认0.5秒
ignored_exceptions:默认只忽略NoSuchElementException异常类型
html代码:

<html>
<meta http-equiv='Content-Type'content='text/html;charset=utf-8'>
	<head>
		<title>你喜欢的水果</title>
		<script>
		function display_alert()
			{
			alert("I am an alert box!!")
			}
		</script>
	</head>
<body>
	<p>请选择你爱吃的水果</p>
	<br>
	<select name='fruit'>
		<option id ='peach'		value='taozi'>桃子</option>
		<option id='watermelon'  value='xigua'>西瓜</option>
	</select>
	<br>
	<input type="button"onclick="display_alert()"value="Display alert box"/>
	<input id ="check"type='checkbox'>是否喜欢吃水果?</input>
	<br><br>
	<input type="text"id="text value="今年夏天西瓜有点甜!">文本框</input>
</body>
</html>

实例

#encoding=utf-8
from selenium import webdriver
import unittest
class VisitByFirefox(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox(executable_path="f:\\geckodriver")
    def test_explicitWait(self):
        import traceback
        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="file:///F:/12.html"
        self.driver.get(url)
        try:
            wait=WebDriverWait(self.driver,10,0.2)
            wait.until(EC.title_is("你喜欢的水果"))
            print("网页标题是(你喜欢的水果)")
            element=WebDriverWait(self.driver,10).until\
                (lambda x:x.find_element_by_xpath\
                    ("//input[@value='Display alert box']"))
            element.click()
            alert=wait.until(EC.alert_is_present())
            print(alert.text)
            alert.accept()
            peach=self.driver.find_element_by_id("peach")
            peachElement=wait.until(EC.element_to_be_selected(peach))
            print("下拉列表中的(桃子)目前处于选中状态")
            wait.until(EC.element_to_be_clickable((By.ID,'check')))
            print("复选框可见并且能被单击")
        except TimeoutException as e:
            print(traceback.print_exc())
        except NoSuchElementException as e:
            print(traceback.print_exc())
        except Exception as e:
            print(traceback.print_exc())
    def tearDown(self):
        self.driver.quit()
if __name__ == '__main__':
        unittest.main()

使用Title属性识别和操作新弹出的浏览器窗口
html代码:

<html>
<meta http-equiv="Content-Type"content="text/html;charset=utf-8"/>
	<head>
		<title>你喜欢的水果</title>	
	</head>
<body>
	<p id='p1'>你爱吃的水果么?</p>
	<br><br>
	<a href ="http://www.sogou.com"target="_blank">sogou 搜索</a>
</body>
</html>

实例 :

#encoding=utf-8
from selenium import webdriver
import unittest
class VisitByFirefox(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox(executable_path="f:\\geckodriver")
    def test_identifyPopUpWindowByTitle(self):
        from selenium.common.exceptions import NoSuchWindowException,TimeoutException
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support.ui import WebDriverWait
        import traceback
        import time
        url="file:///F:/13.html"
        self.driver.get(url)
        WebDriverWait(self.driver,10,0.2).until(EC.element_to_be_clickable((By.LINK_TEXT,'sogou 搜索'))).click()
        all_handless=self.driver.window_handles
        print(self.driver.current_window_handle)
        print(len(all_handless))
        time.sleep(2)
        if len(all_handless)>0:
            try:
                for windowHandle in all_handless:
                    self.driver.switch_to.window(windowHandle)
                    print(self.driver.title)
                    if self.driver.title=="搜狗搜索引擎-上网从搜狗开始":
                        WebDriverWait(self.driver,10,0.2).until\
                            (lambda x:x.find_element_by_id("query")).\
                            send_keys("sogou首页的浏览器窗口被找到")
                        time.sleep(2)
            except NoSuchWindowException as e:
                print(traceback.print_exc())
            except TimeoutError as e:
                print(traceback.print_exc())
        self.driver.switch_to.window(all_handless[0])
        print(self.driver.title)
        self.assertEqual(self.driver.title,"你喜欢的水果")
    def tearDown(self):
        self.driver.quit()
if __name__ == '__main__':
        unittest.main()

通过 页面的关键内容识别和操作新浏览器窗口
html同上一实例

#encoding=utf-8
from selenium import webdriver
import unittest
class VisitByFirefox(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox(executable_path="f:\\geckodriver")
    def test_identifyPopWindowByPageSource(self):
        from selenium.common.exceptions import NoSuchWindowException,TimeoutException
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support.ui import WebDriverWait
        import traceback
        import time
        url="file:///F:/13.html"
        self.driver.get(url)
        WebDriverWait(self.driver,10,0.2).until(EC.element_to_be_clickable((By.LINK_TEXT,'sogou 搜索'))).click()
        handles=self.driver.window_handles
        print(self.driver.current_window_handle)
        print (len(handles))
        if len(handles)>0:
            try:
                for windowHandle in handles:
                    self.driver.switch_to.window(windowHandle)
                    pageSource=self.driver.page_source
                    if "搜狗搜索"in pageSource:
                        WebDriverWait(self.driver,10,0.2).until(lambda x:x.find_element_by_id("query")).send_keys("首页浏览器被找到")
                        time.sleep(2)
            except NoSuchWindowException as e:
                print(traceback.print_exc())
            except TimeoutExcpetion as e:
                print(teaceback.print_exc)
        self.driver.switch_to.window(handles[0])
        self.assertTrue("你爱吃的水果么?"in self.driver.page_source)



    def tearDown(self):
        self.driver.quit()
if __name__ == '__main__':
        unittest.main()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值