selenium常见得等待能分为四种分别是:
隐式等待
常见显示等待
自定义显示等待
线程等待
代码中的wd就是 WebDriver wd=new FirefoxDriver();
1.隐式等待
//页面加载超时时间设置为5s wd.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS); //定位对象时给10s 的时间, 如果10s 内还定位不到则抛出异常 wd.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //异步脚本的超时时间设置成3s wd.manage().timeouts().setScriptTimeout(3, TimeUnit.SECONDS);
self.driver.implicitly_wait(30)
1.隐式等待只能作用于元素的等待。
2.智能等待,如果元素在指定的时间内找到,则不会继续等待,否则在指定时间内未找到元素则抛出NoSuchElementException。
3.作用域是全局的,跟driver的生命周期一样,一般定义在父类中,只要设置隐式等待后,页面所有的元素都会被绑定这种等待机制,只需设置一次,全局有效(只作用于元素),直到driver实例被关闭!
2.常见显示等待
等待的条件 | WebDrive的方法 |
页面元素是否在页面上可用和可被单击 | elementToBeClickable(By locator) |
页面元素处于被选中状态 | elementToBeSelected(WebElement elelment) |
页面元素在页面上是否存在 | presenceOfElementLocated(By locator) |
页面元素是否包特定文本 | textToBePresentInElement(By locator) |
页面元素值 | textToBePresentInElementValue(By locator,java.lang.String text) |
标题 | titleContains(java.lang.String tilte) |
举个例子怎么去用;
WebDriverWait wait =new WebDriverWait(wd,10,1); //最大等待时间为10秒,每一秒检测一次,不设置默认是0.5秒 wait.until(ExpectedConditions.elementToBeClickable(By.className("111"))); // 等等,其他类似.
# 导入显示等待 from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions # 设置10秒的最大等待时间,等待 (By.TAG_NAME, "title") 这个元素点击 WebDriverWait(driver, 10).until( expected_conditions.element_to_be_clickable((By.TAG_NAME, "title")) )
1.除了作用于元素等待还可以实现各种场景的等待,例如页面加载等!
2.智能的等待方式,元素在指定的时间内找到,则不会继续等待,否则抛出TimeOutException.
3.非全局设置,可以针对不同的元素绑定不同的等待机制,推荐优先使用这一种方式.
4.除了可以等待元素的查找,还可以支持多种其他的等待场景(例如:当加载页面的url出现预期值,具体参见ExceptedConditions类的方法)
3.自定义显示等待
WebElement elelment =(new WebDriverWait(wd,10)).until(new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver driver) { // TODO 自动生成的方法存根 return driver.findElement(By.className("112")); } });
Boolean boolen =(new WebDriverWait(wd,10)).until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { // TODO 自动生成的方法存根 return driver.findElement(By.className("11")).getText().contains("你好"); } });
def ceshiren(): # 定义一个方法 def wait_ele_for(driver): # 将找到的元素个数赋值给 eles eles = driver.find_elements(By.XPATH, '//*[@id="site-text-logo"]') # 放回结果 return len(eles) > 0 driver = webdriver.Chrome() driver.get('https://ceshiren.com') # 显示等待10秒,直达 wait_ele_for 返回 true WebDriverWait(driver, 10).until(wait_ele_for)
4.线程等待
try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } wd.findElement(By.className("111")).click();
# 等待十秒time.sleep(10)
线程等待是java语言中的线程类Thread类中的sleep()方法。此等待是很死板的,需要等待时间结束才会执行相关代码。
该方法需要抛出InterruptedException 异常。一般不建议使用
发表评论