版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a6864657/article/details/81107996
为什么需要等待
浏览器进行渲染内容过多, 网速太慢
为了提高脚本的稳定性,我们需要在脚本中增加等待时间,否则报错
强制等待
time.sleep(6)
显式等待
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
#WebDriverWait库 负责循环等待
from selenium.webdriver.support import expected_conditions as EC
#expected_conditions类 负责条件
form selenium.common.exceptions import TimeoutException
#超时异常
判断页面是否已经加载出来
presence_of_all_elements_located
显式等待指定某个条件,然后设置最长等待时间。如果在这段时间还没有找到元素,那么便会抛出异常。
WebDriverWait(driver,10,0.5).until(
EC.presence_of_element_located((By.ID, "myDynamicElement")
)
定一一个WebDriver,将浏览器对象放进去,等待10秒,每隔0.5秒去定位一下想要的元素(此处通过id形式,拿myDynamicElement去定位一个元素)
判断当前的元素是否可以点击
WebDriverWait(driver, 10, 0.5).until(
EC.element_to_be_clickable((By.ID, "myDynamicElement")
)
隐式等待
就是简单地设置一个最大等待时间,单位为秒
所有的元素定位操作都会使用该时间
driver.implicitly_wait(10)