原因:当浏览器加载页面时,页面上的元素并不会同时被加载,因此增加了定位元素的困难(ElementNotVisibleException错误)
WebDriver提供了2种类型的等待
显示等待(WebDriverWait类):使WebDriver等待某个条件成立时继续执行,否则在达到最大时间长时抛出超出时间异常(TimeoutException)
隐式等待(implicitly_wait类):通过一定时长的等待页面上元素加载完成。如果超出了设置的时间长,元素还未被加载,则抛出异常NoSuchElementException
显示等待:
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep,ctime
from selenium.webdriver.support.ui import WebDriverWait #WebDriverWait类提供等待方法
from selenium.webdriver.support import expected_conditions as EC #expected_conditions类提供预制条件判断的方法
from selenium.common.exceptions import NoSuchElementException #抛出异常
driver_path = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe'#调用Chrome浏览器
#显示等待WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,"kw")))
其中:driver-浏览器驱动
Timeout:最长超市,默认以秒为单位
Poll_frequency:检测间隔的(步长)时间,默认为0.5s
Ignored_exceptions:超时后的异常,默认情况下抛出NoSuchElementException
WebDriverWait一般与until()与until_not()方法配合使用
def wb_1():
driver = webdriver.Chrome(executable_path=driver_path)
driver.get('http://www.baidu.com')
driver.find_element_by_id('kw')
element = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,"kw")))
element.send_keys("python")
time.sleep(2)
driver.quit()
# 设置元素等待时间-显示等待2
#使用is_displayed()方法来判断元素是否可见
def wb_2():
driver = webdriver.Chrome(executable_path=driver_path)
driver.get('http://www.baidu.com')
#driver.find_element_by_id('kw')
el = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,"kww")))
#判断输入框是否可见,可见在进行它的操作,否则执行else操作
if el.is_displayed():
el.send_keys("百度")
driver.find_element_by_id('su').click()
time.sleep(2)
else: # raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: essage:
print("搜索框不存在!!")
driver.quit()
隐式等待:
#implicitly_wait隐式等待
#判断某元素,如果超过10s未发现,则抛出异常
#如果在5s内发现,则对该元素进行操作
def wb_3():
driver = webdriver.Chrome(executable_path=driver_path)
driver.implicitly_wait(10)#设置隐式等待最长时间10s
driver.get('http://www.baidu.com')
try:
print(ctime())
driver.find_element_by_id('k1w').send_keys("python")
driver.find_element_by_id('su').click()
sleep(2) #固定休眠时间,等待xx秒
except NoSuchElementException as e:
print(e)
finally:
print(ctime())
driver.quit()