隐式等待
在页面刷新加载时,页面元素还没有出来,这个时候如果去找元素就会找不到报错
或者点了一个菜单,页面加载时
用笨办法,就是用sleep等待固定的时间,这种浪费的时间比较多,就可以用隐式等待,只等待页面加载完,就不等待了,效率会提高一些
from selenium import webdriver
import time
# 创建浏览器驱动对象
from selenium.webdriver.common.by import By
driver = webdriver.Chrome() # 参数写浏览器驱动文件的路径,若配置到环境变量就不用写了
# 访问网址
driver.get("http://42.192.62.186:8088/index.html#/")
driver.maximize_window()
# 账号密码
driver.find_element(By.CSS_SELECTOR, '#username').send_keys('sq3')
driver.find_element(By.CSS_SELECTOR, '#password').send_keys('123')
driver.find_element(By.CSS_SELECTOR, '#code').send_keys('999999')
driver.find_element(By.CSS_SELECTOR,"#submitButton").click()
time.sleep(1)
driver.refresh()
"""隐式等待, 就不需要下面两个强制等待了"""
driver.implicitly_wait(30)
# time.sleep(1) # 刷新頁面有延迟
driver.find_element(By.XPATH,'//*[contains(text(),"文件上传")]').click()
time.sleep(1)
driver.find_element(By.XPATH,'//*[contains(text(),"单文件上传")]').click()
# time.sleep(1) # 渲染页面有延时
ele= driver.find_element(By.CSS_SELECTOR, '#cover')
显示等待
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC
可以用这个等待类,来进行针对性的等待
表示,我只针对要等的元素,进行等待, 而不是像隐式等待那样,等待页面全部
如下:是对二级菜单元素的等待
from selenium import webdriver
import time
# 创建浏览器驱动对象
from selenium.webdriver.common.by import By
driver = webdriver.Chrome() # 参数写浏览器驱动文件的路径,若配置到环境变量就不用写了
# 访问网址
driver.get("http://42.192.62.186:8088/index.html#/")
driver.maximize_window()
# 账号密码
driver.find_element(By.CSS_SELECTOR, '#username').send_keys('sq3')
driver.find_element(By.CSS_SELECTOR, '#password').send_keys('123')
driver.find_element(By.CSS_SELECTOR, '#code').send_keys('999999')
driver.find_element(By.CSS_SELECTOR,"#submitButton").click()
time.sleep(1)
driver.refresh()
# driver.implicitly_wait(30)
time.sleep(1) # 刷新頁面有延迟
driver.find_element(By.XPATH,'//*[contains(text(),"文件上传")]').click()
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# time.sleep(1)
"""
我们等待最多10秒,直到页面上出现XPATH为"xxxx"的元素
如果在10秒内找到了该元素,就会继续操作
(driver,10 ,0.5) # 默认轮询时间为0.5
"""
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH,'//*[contains(text(),"单文件上传")]'))
)
element.click()
- presence_of_element_located 判断某元素是否被加到DOM树,不一定可见 (上面代码用到的)
- visibility_of_element_located 判断某元素是否可见
使用场景,当某个一个元素加载特别缓慢,可以对它进行显示等待