熟练掌握Selenium工具核心功能总纲(一)

发表于:2021-9-16 09:33

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:佚名    来源:掘金

  一、Selenium版本区别
  起初这个开源项目2004年是使用js实现的,由原来的(js的核心库selenium core、selenium RC、selenium IDE):selenium1<支持录制>、webdriver<另一伙人开发的>,再是两者合并selenium2、继而selenium3、到现在selenium4
  selenium2:具有来自webdriver清晰的面向对象API,以最佳的方式与浏览器进行交互,支持多种浏览器和多语言绑定;
  selenium3:浏览器交互基JSON-wire协议,因此需要对API进行编码和解码;
  selenium4:它遵循W3C标准协议,驱动程序和浏览器之间的通信遵循标准程序,不需要对API进行编码和解码,因此直接进行通信。
  二、Selenium工具的基本使用
  1、元素定位的八大方法
  其中linkText及partialLinkText方法只能是在a标签内才可使用该方法,也可以是被包含在a标签的超链接,例如:
  <a class="_yb_vxdx4" href="https://mail.yahoo.com/?pspid=2023538075&amp;activity=ybar-mail" data-ylk="slk:Mail;elm:btn;sec:ybar;subsec:mailprev;itc:0;tar:mail.yahoo.com;" id="ybarMailLink" aria-label="Check your mail" aria-haspopup="true" aria-expanded="true" data-redirect-params="pspid=[[pspid]]&amp;activity=ybar-mail" data-rapid_p="24" data-9y="1">  
  <span class="ybar-icon-sprite _yb_mu95s _yb_1yf3n">Sign in</span>     
  <span class="_yb_152j2 _yb_2al7h">Mail</span>
  </a>
  · By.linkText("Mail")
  · By.partialLinkText("Sign")
  其中tagName和className,这两个可能极少使用,因为少有一个标签名只在html使用一次或者class样式只引用一次;so,你懂得,几乎用不上。如上
  By.className("_yb_vxdx4") 
  By.tagName("a")
  · 所以优先使用定位页面元素的方法顺序为:id > name > cssSelector > xpath
  · 基本情况是:selenium中定位页面元素完成UI自动化,那么掌握xpath就是核心技术
  2、WebDriver/Selenium的原理剖析:
  在环境变量中(system32目录),执行脚本,系统能找到chromedriver并启动,通过chromedriver服务去驱动浏览器执行打开url、操作页面元素的操作;然后返回给脚本的状态。
  先了解selenium的发展历程,selenium1原来是个JavaScript库,后引入selenium RC即Server && Client Librarise,而后是selenium2,
  又融入了一个WebDriver核心库,所以selenium2合并之后又被称为WebDriver,至于为什么它能支持不同的脚本语言,因为它遵守json wire protocol,
  是以json格式的数据进行传递(脚本与浏览器)交互;所以我们能理解的原理是:开发脚本支持多种语言,调用WebDriver对应的api驱动浏览器并进行页面元素操作,
  脚本(client)与浏览器(server)之间基于json wire protocol进行数据传递并响应;那么就不要管它后面的selenium3、selenium4,没用到这些版本的特性就与这个版本无关。
  如果chromedriver不在系统变量中<放在system32这个目录中>,创建的driver对象能找到这个服务,需要使用System.setProperty方法
  System.setProperty("webdriver.chrome.driver","chromedriver.exe路径");
  3、webdriver的核心方法和属性,是webdriver对象,譬如:WebDriver driver=new ChromeDriver()
  访问网址:get()、navigate().to()
  4、webelement的核心方法和属性
  · 状态判断is开头的方法,如isSelected()
  · 元素操作,如发送指定:sendKeys(),清除文本:clear(),退出/关闭浏览器:quit()/close(),点击:click()
  · 获取标签的属性:getAttribute("")
  · 获取标签的文本值:getText()
  5、form表单操作、frame和iframe的定位及frame的切入和切出:
  关键方法:switchTo()
  6、checkbox和radiobutton的定位技巧
  这里可以演示一个关于radiobutton的案例:逐一选择单选按钮,dom如下:
  <html>
  <title></title>
  <body>
  <div align="center" id="radio-btn-example">
  <fieldset>
  <legend>Radio Button 示例</legend>
  <label for="apple"> <input id="appleradio" value="apple"
  name="fruit" type="radio"> 苹果<br />
  </label> <label for="orange"> <input id="orangeradio" value="orange"
  name="fruit" type="radio"> 桔子<br />
  </label> <label for="peach"> <input id="peachradio" value="peach"
  name="fruit" type="radio"> 桃子<br />
  </label>
  </fieldset>
  </div>
  </body>
  </html>
  以上有三个单选按钮,挨个点击一遍:
  findElement(By.id("appleradio")).click(); 
  findElement(By.id("orangeradio")).click(); 
  findElement(By.id("peachradio")).click();
  上面的写法没有什么不对,假使如果某个radio是默认选项呢?那怎么确定是你选择的呢?所以,我们可以找出所有input标签://input[@type='radio' and @name='fruit']
  List<WebElement> eles=driver.findElements(By.xpath("//input[@type='radio' and @name='fruit']));
  for(WebElement el:eles){
      // 判断元素是否被选中,否则不点击了
      if(!el.isSelected()){
          el.click();
          System.out.prinln("判断是否被选择中:"+el.isSelected());
      }
  }
  // 上面是高级for的遍历方法,下面是个普通for循环
  for(int i=0;i<eles.size();i++){
      if(eles.get(i).isSelected()){
          eles.get(i).click();
          System.out.prinln("判断是否被选择中:"+el.isSelected());
      }
  }
  复选框。input标签属性type=checkbox:
  <html>
  <title>复选框</title>
  <body>
  <div align="center" id="checkbox-example">
  <fieldset>
  <legend>Checkbox 示例</legend>
  <label for="apple"> <input id="applecheck" value="apple"
  name="fruit" type="checkbox"> 苹果<br />
  </label> <label for="orange"> <input id="orangecheck" value="orange"
  name="fruit" type="checkbox"> 桔子<br />
  </label> <label for="peach"> <input id="peachcheck" value="peach"
  name="fruit" type="checkbox"> 桃子<br />
  </label><label for="bananer"> <input id="bananercheck" value="bananer"
  name="fruit" type="checkbox"> 香蕉<br />
  </label>
  </fieldset>
  </div>
  </body>
  </html>
  复选框操作类似单选按钮,可以通过查找id唯一元素点击:
  findElement(By.id("applecheck")).click(); 
  findElement(By.id("bananercheck")).click(); 
  findElement(By.id("orangecheck")).click();
  假使input标签可以指定默认勾选<在input标签中设置checked即为默认选中>,那么元素操作它的时候,可能是取消,所以可以加个条件判断是否勾选,如果勾选则不选或取消,按需求实现:
  先通过元素查找所有元素:xpath://input[@type='checkbox' and @name='fruit']
  driver.get(System.getProperty("user.dir") + "/drivers/checkbox.html");
  // 找出所有复选框元素
  List<WebElement> elements = driver.findElements(By.xpath("//input[@type='checkbox' and @name='fruit']"));
  // 遍历复选框元素
  for (WebElement ele : elements) {
  // 判断是否已选择
      if (ele.isSelected()) {
          System.out.println(ele.getAttribute("value") + ",是默认选择的");
      } else {
          ele.click();
          System.out.println(ele.getAttribute("value") + ",是否选中:"+ ele.isSelected());
          }
  }
  7、使用select类实现下拉列表定位、多选列表框
  dom元素示例:
  <html>
  <title></title>
  <body>
  <script>
  function showAlert() {
  document.getElementById("multiple-select-example").multiple=true;
  var value = document.getElementById("multiple-select-example");
  if (value.value == "orange") {
  alert("选择了:橘子");
  } else if (value.value == "apple") {
  alert("选择了:苹果");
  } else if (value.value == "banner") {
  alert("选择了:香蕉");
                  
  }else if (value.value == "peach") {
  alert("选择了:桃子");
                  }else {
  alert("请选择");
  }
  }
  </script>
  <div align="center">
  <select id="multiple-select-example" multiple="" size="4"
  name="multiple-select-example">
  <option value="apple">苹果</option>
  <option value="orange">桔子</option>
  <option value="peach">桃子</option>
  <option value="banner">香蕉</option>
  </select> <input id="alertbtn" class="btn-style" value="Alert"
  onclick="showAlert()" type="submit">
  </div>
  </body>
  </html>
  解释一下上面的代码:多选框使用select标签,为什么证明选择的内容可以被正确选中提交,添加了input标签定义type属性为submit,写了js用于获取select标签选中的内容。
  假如我们知道如何xpath写表达式,如://option[@value='peach'],这样就可以选中桃子:
  // 或者放置系统system32目录下作为环境变量
  System.setProperty("webdriver.chrome.driver",
                  "drivers/chromedriver.exe");
  WebDriver driver = new ChromeDriver();
  driver.get(System.getProperty("user.dir") + "/drivers/gupiao.html");
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  driver.findElement(By.xpath("//option[@value='peach']")).click();
  Thread.sleep(2000);
  driver.findElement(By.id("alertbtn")).click();
  Thread.sleep(2000);
  Alert alert = driver.switchTo().alert();
  alert.accept();
  driver.quit();
  思考:
  但是有一个问题,即是多选框,那么就不止选择一个,如何实现选择多个呢?在按键操作是可以通过shift可以实现,那么selenium呢?实际是可以操作多次;
  driver.findElement(By.xpath("//option[@value='peach']")).click(); 
  driver.findElement(By.xpath("//option[@value='banner']")).click();
  这里介绍一个selenium工具中的Select类来实现:
  WebElement element=driver.findElement(By.id("multiple-select-example"));
  Select sel=new Select(element);
  // 根据标签属性值选择
  sel.selectByValue("peach");
  Thread.sleep(2000);
  // 根据索引
  sel.selectByIndex(1);
  Thread.sleep(2000);
  // 根据标签text文本
  sel.selectByVisibleText("香蕉");
  List<WebElement> selOptions=sel.getAllSelectedOptions();
  for(WebElement el:selOptions){
    // 输出选择的option文本
          System.out.println(el.getText());
  }
  Thread.sleep(2000);
  // 取消选择
  sel.deselectAll();

  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号