强制等待
time.sleep(3)这种方式简单粗暴,必须等XX时间,不管你浏览器是否加载完了,程序都得等3秒,然后继续执行下面的代码,太死板,严重影响程序的执行速度。可以作为调试用,有时代码里面也这样用。
隐式等待
implicitly_wait(xx)设置一个最长等待时间,如果在规定时间内网页加载完成,则执行下一步,否则一直等到时间截止,然后执行下一步。好处是不用像强制等待(time.sleep(n))方法一样死等固定的时间n秒,可以在一定程度上提升测试用例的执行效率。不过这种方法也从在一个弊端,那就是程序会一直等待整个页面加载完成,也就是说浏览器窗口标签中不再出现转动的小圈圈,再会继续执行下一步,比如有些时候想要的页面元素早就加载完了,但由于个别JS资源加载稍慢,此时程序仍然会等待页面全部加载完成才继续执行下一步,这无形中加长了测试用例的执行时间。
注意:隐式等待时间只需要被设置一次,然后它将在driver的整个生命周期都起作用。
# encoding=utf-8
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 = "d:\\geckodriver")
self.driver = webdriver.Ie(executable_path="d:\\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秒内返回则继续执行后续脚本
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()
except (NoSuchElementException, TimeoutException) as e:
# 打印异常的堆栈信息
traceback.print_exc()
def tearDown(self):
# 退出IE浏览器
self.driver.quit()
if __name__ == '__main__':
unittest.main()
我想等我要的元素出来之后就下一步怎么办?有办法,这就要看selenium提供的另一种等待方式——显性等待wait了。
显式等待
通过selenium.webdriver.support.ui模块提供的WebDriverWait类,再结合该类的until()和until_not()方法,并自定义好显式等待的条件,然后根据判断条件进行灵活的等待。
显式等待的工作原理:程序每隔xx秒看一眼,如果条件成立了,则执行下一步,否则继续等待,直到超过设置的最长时间,然后抛出TimeoutException。
#encoding=utf-8
from selenium import webdriver
import time
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 = "d:\\IEDriverServer")
driver.get("http://www.sogou.com")
input_box=driver.find_element_by_id("query")
wait = WebDriverWait(driver, 10, 0.2)
wait.until(EC.visibility_of(input_box))
input_box.send_keys(u"北京新发地")
wait.until(EC.element_to_be_clickable((By.ID ,"stb")))
button=driver.find_element_by_id("stb")
button.click()
time.sleep(3)
driver.close()