selenium常见元素操作之三大等待
selenium常见元素操作之三大等待
from selenium import webdriver
import time
#浏览器会话的开始
driver = webdriver.Chrome()
#driver.implicitly_wait(30) #添加全局等待时间
driver.get(“http://www.baidu.com”) #get函数默认等待静态页面加载完成
driver.find_element_by_xpath(’//div[@id=“u1”]//a[@name=“tj_login”]’).click() #点击登录按钮
#当操作引起界面发生变化的时候,一定要加等待
三种等待
方式一:强制等待 sleep(秒)
time.sleep(5)
方式二:智能等待(隐形等待) implicitly_wait 设置全局等待时间,只需要添加一次,添加在打开浏览器之前
#driver.implicitly_wait(30) #设置等待最大时间30秒,超过30秒报错TimeoutException,30秒之内何时出现何时进入下一步操作
方式三:智能等待(显性等待) 明确的条件(元素出现,窗口打开等…) 等待+条件
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
WebDriverWait类:显性等待类
#WebDriverWait(driver,等待时常,轮循周期).until() /until_not()
expected_conditions模块:提供一系列希望发生的条件(有很多方法,可根据需要学习,举例如下)
#1.元素存在:html里面存在,能找到
#EC.presence_of_element_located
#2.元素可见:存在并且可见,有大小
#EC.visibility_of_element_located
#3.元素可用:存在-可见-并可用(只读\不可点击等为不可用)
#EC.element_to_be_clickable
#等待条件表达
#step1: locator = (定位类型,定位表达式) #定位到做断言的元素
locator = (By.ID,‘TANGRAM__PSP_11__footerULoginBtn’)
#等待元素可见
#step2: EC.visibility_of_element_located(locator) #判断条件,元素可见
WebDriverWait(driver,30).until(EC.visibility_of_element_located(locator))
#step3:辅助等待 0.5s
time.sleep(0.5)
driver.find_element_by_id(“TANGRAM__PSP_11__footerULoginBtn”).click() #点击用户名登录