selenium中的等待时间有3种:sleep(second);WebDricerWait(driver,timeout,poll_frequency,ignored_exceptions);implicicitly(second)
1.sleep(second) :强制等待,封装在time中的sleep类中
导入方法及使用方法如下:
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 # 导入webdriver包 4 from selenium import webdriver 5 from time import sleep 6 driver = webdriver.Firefox() #创建火狐对象 7 driver.get("https://www.baidu.com/") #打开baidu 8 sleep(5) #等待5毫秒 9 driver.quit() #关闭浏览器
2.WebDricerWait(driver,timeout,poll_frequency,ignored_exceptions) 显式等待,当找到要校验的元素后就继续执行下面的程序,非强制等待
driver:浏览器驱动
timeout:最长超时,秒为单位
poll_frequency:检测间隔(步长)时间,默认为0.5s
ignored_exceptions:超时后的异常信息,默认情况下抛出 NoSuchElementException
webDriverWait 一般与until()与until_not()方法配合使用
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 from selenium import webdriver 4 from time import sleep 5 from selenium.webdriver.common.by import By 6 from selenium.webdriver.support.ui import WebDriverWait 7 from selenium.webdriver.support import expected_conditions as EC 8 #WebDriverWait 显式等待 9 driver = webdriver.Firefox() 10 driver.get("https://www.baidu.com/") 11 el = driver.find_element_by_xpath('//*[@id="kw"]') 12 element = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,"kw"))) 13 element.send_keys("selenium") 14 driver.find_element_by_xpath('//*[@id="su"]').click() 15 sleep(5) 16 driver.quit()
3.implicicitly(second)隐式等待,设置最长等待时长,如果在特定时间内未找到元素则抛出NoSuchElementException异常
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 #隐式等待 4 from selenium import webdriver 5 from time import sleep,ctime 6 from selenium.common.exceptions import NoSuchElementException 7 driver = webdriver.Firefox() 8 driver.implicitly_wait(10) 9 driver.get("https://www.baidu.com/") 10 try: 11 print(ctime()) 12 driver.find_element_by_xpath('//*[@id="kw"]').send_keys("selenium") 13 driver.find_element_by_xpath('//*[@id="su"]').click() 14 except NoSuchElementException as E: 15 print(E) 16 finally: 17 print(ctime()) 18 driver.quit()
4.总结
隐式等待会等driver完全加载完成(如js、css等);显示等待仅仅校验需要加载的元素是否存在;强制等待字面很好理解,就不多说。大家可根据需求自行选择。