• java工作复习——4大时间等待——显示等待(转载)


      休眠 显示等待 隐式等待
    含义 脚本在执行到某一位置时做固定时间的休眠。 等待某个条件成立时继续执行,否则在达到最大时长时抛出超时异常。 通过一定的时长等待页面上某元素加载完成。
    Java Thread.sleep(时间) WebDriverWait wait = new WebDriverWait(driver, 时间) driver.manage().timeouts().implicitlyWait(时间, TimeUnit.SECONDS)
    Python sleep(时间) WebDriverWait(driver, 最长超时时间, 间隔时间(默认0.5S), 异常) driver.implicitly_wait(时间)
    Ruby sleep(时间) wait = selenium::webdriver::wait.new(:timeout => 时间) driver.manage.timeouts.implicit_wait = 时间
    注意:Java中休眠方法的单位是毫秒,其他方法的时间单位都为秒( 1秒=1000毫秒)

    **代码时间 **

    ε(┬┬﹏┬┬)3 虽然只是简简单单的等待,但是基于等待的对象不同、不同对象有不同的等待操作,所以有多种或者自定义显示等待方法(之前文章的代码主要采用休眠方法,因此在此不做演示)。光光文字无法阐述完整,我们先看个表格,然后关门放代码ฅʕ•̫͡•ʔฅ

    说明 显示等待方法
    Java Python Ruby
    需导入类 org.openqa.selenium.support.ui.ExpectedConditions expected_conditions -
    判断当前页面的标题是否等于预期 titleIs title_is -
    判断当前页面的标题是否包含预期字符串 titleContains title_contains -
    判断元素是否加在DOM树里(不代表该元素一定可见) presenceOfElementLocated presence_of_element_located -
    判断元素是否可见(参数为定位) visibilityOfElementLocated visibility_of_element_located -
    同上个方法(参数为定位后的元素) visibilityOf visibility_of -
    判断是否至少有一个元素存在于DOM数中 presenceOfAllElementsLocatedBy presence_of_all_elements_located -
    判断某个元素中的text是否包含了预期的字符串 textToBePresentInElement text_to_be_present_in_element -
    判断某个元素的vaule属性是否包含了预期的字符串 textToBePresentInElementValue text_to_be_present_in_element_value -
    判断该表单是否可以切换进去
    如果可以,返回true并且switch进去,否则返回false
    frameToBeAvailableAndSwitchToIt frame_to_be_available_and_switch_to_it -
    判断某个元素是否不存在于DOM树或不可见 invisibilityOfElementLocated invisibility_of_element_located -
    判断元素是否可见是可以点击的 elementToBeClickable element_to_be_clickable -
    等到一个元素从DOM树中移除 stalenessOf staleness_of -
    判断某个元素是否被选中,一般用在下拉列表 elementToBeSelected element_to_be_selected -
    判断某个元素的选中状态是否符合预期(参数为定位后的元素) elementSelectionStateToBe element_selection_state_to_be -
    同上个方法(参数为定位) - element_located_selection_state_to_be -
    判断页面上是否存在alert alertIsPresent alert_is_present -
    (;´༎ຶД༎ຶ`)并不是我想偷懒把Ruby的省略了,我找了许多资料都没有找到Selenium::WebDriver中包含此种类型的方法,后期发现好方法在做添加~~~

    Java

    显示等待

    复制代码
     1 package JavaTest;
     2 
     3 import java.util.NoSuchElementException;
     4 import org.openqa.selenium.By;
     5 import org.openqa.selenium.WebDriver;
     6 import org.openqa.selenium.WebElement;
     7 import org.openqa.selenium.firefox.FirefoxDriver;
     8 import org.openqa.selenium.support.ui.ExpectedCondition;
     9 import org.openqa.selenium.support.ui.ExpectedConditions;
    10 import org.openqa.selenium.support.ui.WebDriverWait;
    11 
    12 public class Test {
    13     public static void main(String[] arg) throws InterruptedException
    14     {
    15         WebDriver driver = new FirefoxDriver();
    16         driver.get("http://www.baidu.com/");
    17 
    18         /*
    19          * 设置显示等待时长:10秒;
    20          */
    21         WebDriverWait wait = new WebDriverWait(driver, 10);
    22         
    23         // 显示等待:标题是否出现:
    24         try {
    25             wait.until(ExpectedConditions.titleContains("百度一下,你就知道"));
    26             System.out.println("百度首页的标题已出现");
    27         } catch (NoSuchElementException e) { //如果标题没有找到,则抛出NoSuchElementException异常。
    28             e.printStackTrace();
    29             System.out.println("未找到百度首页的标题");
    30         }
    31         
    32         //显示等待:搜索框是否出现
    33         try {
    34             wait.until(ExpectedConditions.presenceOfElementLocated(By.id("su")));
    35             System.out.println("百度首页的搜索输入框已出现");
    36         } catch (NoSuchElementException e) { //如果标题没有找到,则抛出NoSuchElementException异常。
    37             e.printStackTrace();
    38             System.out.println("未找到百度首页的输入框");
    39         }
    40                 
    41         //显示等待:页面搜索按钮是否可以被点击;
    42         try {
    43             wait.until(ExpectedConditions.elementToBeClickable(By.id("kw")));
    44             System.out.println("百度首页的搜索按钮可以被点击");
    45         } catch (NoSuchElementException e) { //如果标题没有找到,则抛出NoSuchElementException异常。
    46             e.printStackTrace();
    47             System.out.println("未找到百度首页的搜索按钮");
    48         }
    49 
    50         /*
    51          * 自定义显示等待,获取页面元素//*[@id='cp']的文本值
    52          */
    53         String text = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<String>() {
    54             @Override
    55             public String apply(WebDriver driver){
    56             return driver.findElement(By.xpath("//*[@id='cp']")).getText();
    57             }
    58         });
    59         System.out.println(text); //打印文本值
    60         
    61         /*
    62          * 自定义显示等待,在等待代码中找到某个元素;
    63          */
    64         WebElement textInputBox = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<WebElement>() {
    65             @Override
    66             public WebElement apply(WebDriver driver){
    67             return driver.findElement(By.xpath("//*[@id='kw']"));
    68             }
    69         });
    70         textInputBox.sendKeys("自定义显式等待,在等待代码中找到某个元素");
    71         
    72         driver.close();
    73     }
    74 }
    复制代码

    隐式等待

    复制代码
     1 package JavaTest;
     2 
     3 import java.util.NoSuchElementException;
     4 import java.util.concurrent.TimeUnit;
     5 import org.openqa.selenium.By;
     6 import org.openqa.selenium.Keys;
     7 import org.openqa.selenium.WebDriver;
     8 import org.openqa.selenium.firefox.FirefoxDriver;
     9 import org.openqa.selenium.interactions.Actions;
    10 
    11 public class Test {
    12     public static void main(String[] arg) throws InterruptedException
    13     {
    14         WebDriver driver = new FirefoxDriver();
    15 
    16         /*
    17          *设置全局隐式等待时间
    18           *使用implicitlyWait方法,设定查找元素的等待时间
    19          *当调用findElement方法的时候,没有立刻找到元素,就会按照设定的隐式等待时长等待下去
    20          *如果超过了设定的等待时间,还没有找到元素,就抛出NoSuchElementException异常
    21          */
    22         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    23         driver.get("http://www.baidu.com/");
    24         
    25         try
    26         {
    27             driver.findElement(By.xpath("//*[@class='s_ipt']")).sendKeys("Java");  // 对百度输入框赋值
    28             driver.findElement(By.id("kw1")).sendKeys(Keys.chord(Keys.CONTROL,"A")); // 页面没有id为kw1的元素,此处报错
    29         }catch(NoSuchElementException e) {
    30             //如果元素没有找到,则抛出NoSuchElementException异常。
    31             e.printStackTrace();
    32         }
    33         finally
    34         {
    35             driver.close();
    36         }
    37     }
    38 }
    复制代码

    Python

    显示等待

    复制代码
     1 from selenium import webdriver
     2 from selenium.webdriver.common.by import By
     3 from selenium.webdriver.support import expected_conditions as EC
     4 
     5 # 启动Firefox浏览器
     6 from selenium.webdriver.support.wait import WebDriverWait
     7 
     8 driver = webdriver.Firefox()
     9 driver.get('http://www.baidu.com')
    10 
    11 # 设置显示等待时间为10S
    12 wait = WebDriverWait(driver, 10)
    13 
    14 # 显示等待:页面标题是否包含“百度一下”
    15 try:
    16     wait.until(EC.title_contains('百度一下'))
    17     print("百度首页的标题已出现")
    18 except Exception as e:
    19     print(e.args[0]) # 显示报错原因
    20     print('未找到百度首页的标题')
    21 
    22 # 显示等待:元素是否可见
    23 try:
    24     element = wait.until(EC.visibility_of(driver.find_element(By.ID,'kw')))
    25     element.send_keys('Python')
    26     print('百度首页的搜索输入框可见')
    27 except Exception as e:
    28     print(e.args[0])
    29     print('百度首页的搜索输入框不可见')
    30 
    31 # 显示等待:元素是否可以点击
    32 try:
    33     element = wait.until(EC.element_to_be_clickable((By.XPATH,"//*[@id='su']")))
    34     element.click()
    35     print('百度首页的搜索按钮可以被点击')
    36 except Exception as e:
    37     print(e.args[0])
    38     print('未找到百度首页的搜索按钮')
    复制代码

    隐式等待

    复制代码
     1 from time import *
     2 from selenium import webdriver
     3 from selenium.webdriver.common.by import By
     4 from selenium.webdriver.common.keys import Keys
     5 from selenium.common.exceptions import NoSuchElementException
     6 
     7 # 启动Firefox浏览器
     8 driver = webdriver.Firefox()
     9 
    10 driver.implicitly_wait(10) # 设置隐式等待时间10S
    11 driver.get('http://www.baidu.com')
    12 
    13 try:
    14     print(ctime())  # 当前时间
    15     driver.find_element(By.XPATH,"//*[@class='s_ipt']").send_keys('Python')  # 对百度输入框赋值
    16     driver.find_element(By.ID,'kw2').send_keys(Keys.CONTROL, 'A')  # 页面没有id为kw2的元素,此处报错
    17 except NoSuchElementException as e:
    18     print(e) # 显示报错信息
    19 finally:
    20     print(ctime()) # 此处检查等待后的时间
    21     driver.close() # 结束
    复制代码

    Ruby

    显示等待

    复制代码
     1 class Baidu
     2   require 'rubygems'
     3   require 'selenium-webdriver'
     4 
     5   # 打开firefox并输入网址
     6   driver = Selenium::WebDriver.for :firefox
     7   driver.navigate.to "http://www.baidu.com"
     8 
     9   # 设置显式等待时间10S
    10   wait = Selenium::WebDriver::Wait.new(:timeout => 10)
    11 
    12   # 显示等待:元素是否显示(return [Boolean])
    13   begin
    14     wait.until {driver.find_element(:id => 'kw').displayed?}
    15     puts "百度首页的搜索输入框可见"
    16   rescue => e
    17     puts e.message # 显示报错信息
    18   end
    19 
    20   # 显示等待:指定元素是否为空
    21   begin
    22     wait.until {driver.find_element(:id => 'kw').attribute('value').empty?}
    23     puts "百度首页的搜索输入框为空"
    24   rescue => e
    25     puts e.message # 显示报错信息
    26   end
    27   # 显示等待:页面标题是否是指定标题
    28   begin
    29     wait.until {driver.title.eql?'百度一下,你就知道'}
    30     puts "页面标题是百度一下,你就知道"
    31   rescue => e
    32     puts e.message # 显示报错信息
    33   end
    34 
    35 
    36   # 显示等待:页面标题是否包含“百度一下”
    37   begin
    38     wait.until {driver.title.include?'百度一下'}
    39     puts "百度首页的标题已出现"
    40   rescue => e
    41     puts e.message # 显示报错信息
    42   ensure
    43     driver.quit
    44   end
    45 end
    复制代码

    隐式等待

    复制代码
     1 class Baidu
     2   require 'rubygems'
     3   require 'selenium-webdriver'
     4 
     5   # 打开firefox并输入网址
     6   driver = Selenium::WebDriver.for :firefox
     7 
     8   # 设置隐式等待时间10S
     9   driver.manage.timeouts.implicit_wait = 10
    10   driver.navigate.to "http://www.baidu.com"
    11 
    12   begin
    13     driver.find_element(:name => 'wd').send_keys('ruby')  # 对百度输入框赋值
    14     driver.find_element(:id => 'kw3').send_keys [:control,'a'] # 页面没有id为kw3的元素,此处报错
    15   rescue Selenium::WebDriver::Error::NoSuchElementError => e
    16     puts e.message # 显示报错信息
    17   ensure
    18     driver.close #退出程序
    19   end
    20 end
  • 相关阅读:
    Sam小结和模板
    K-string HDU
    str2int HDU
    Common Substrings POJ
    Reincarnation HDU
    实体框架自动迁移出现异常。
    C#代码配置IIS 操纵IIS
    MVC项目页面获取控制器的信息
    通过js判断手机访问跳转到手机站
    "Could not load file or assembly 'DTcms.Web.UI' or one of its dependencies. 拒绝访问。" 的解决办法
  • 原文地址:https://www.cnblogs.com/xiaobaibailongma/p/12752144.html
Copyright © 2020-2023  润新知