多测师是一家拥有先进的教学理念,强大的师资团队,业内好评甚多的接口自动化测试培训机构!

17727591462

联系电话

您现在所在位置:接口自动化测试培训 > 新闻资讯

WebDriver中使用JQuery选择器-自动化测试

更新时间:2022-05-05 09:15:56 作者:多测师 浏览:174

  1.在已加载了JQuery的页面上可以直接使用JQuery选择器

  例如www.jquery.com网站,如果我们想定位红框中导航栏中的偶数为就可以使用jquery的伪选择器:even

  WebDriver中使用JQuery选择器

  具体实现如下

WebDriver中使用JQuery选择器-自动化测试

  packagecom.example.tests;

  importstaticorg.junit.Assert.*;

  importjava.util.*;

  importorg.junit.*;

  importorg.openqa.selenium.*;

  importorg.openqa.selenium.ie.InternetExplorerDriver;

  publicclasstest{

  WebDriverdriver=newInternetExplorerDriver();

  JavascriptExecutorjse=(JavascriptExecutor)driver;

  @Test

  publicvoidjQueryTest(){

  driver.get("http://www.jquery.com/");

  //在executeScript中调用jQuery.find(jquerySelector);

  Listelements=

  (List)jse.executeScript("returnjQuery.find"+"('.menu-itema:even')");

  assertEquals(3,elements.size());

  assertEquals("Download",elements.get(0).getText());

  assertEquals("Blog",elements.get(1).getText());

  assertEquals("BrowserSupport",elements.get(2).getText());

  driver.close();

  }

  }

  2.另一种情况就是页面没有另载jQuery,我们需要先判断再自已手动注入,以百度为例,百度首页是没有加载的

  packagecom.example.tests;

  importstaticorg.junit.Assert.*;

  importjava.util.*;

  importorg.junit.*;

  importorg.openqa.selenium.*;

  importorg.openqa.selenium.ie.InternetExplorerDriver;

  publicclassSelenium2{

  WebDriverdriver=newInternetExplorerDriver();

  JavascriptExecutorjse=(JavascriptExecutor)driver;

  @Test

  publicvoidjQueryTest(){

  driver.get("http://www.baidu.com/");

  injectjQueryIfNeeded();

  Listelements=(List)jse

  .executeScript("returnjQuery.find('#nva')");

  assertEquals(7,elements.size());//验证超链接的数量

  for(inti=0;i

  System.out.print(elements.get(i).getText()+"、");

  }

  driver.close();

  }

  privatevoidinjectjQueryIfNeeded(){

  if(!jQueryLoaded())

  injectjQuery();

  }

  //判断是已加载jQuery

  publicBooleanjQueryLoaded(){

  Booleanloaded;

  try{

  loaded=(Boolean)jse.executeScript("return"+"jQuery()!=null");

  }catch(WebDriverExceptione){

  loaded=false;

  }

  returnloaded;

  }

  //通过注入jQuery

  publicvoidinjectjQuery(){

  jse.executeScript("varheadID="

  +"document.getElementsByTagName(\"head\")[0];"

  +"varnewScript=document.createElement('script');"

  +"newScript.type='text/javascript';"+"newScript.src="

  +"'http://ajax.googleapis.com/ajax/"

  +"libs/jquery/1.7.2/jquery.min.js';"

  +"headID.appendChild(newScript);");

  }

  }

  以上内容为大家介绍了自动化测试中的WebDriver中使用JQuery选择器,本文由多测师亲自撰写,希望对大家有所帮助。了解更多自动化测试相关知识:https://www.aichudan.com/xwzx/

联系电话

17727591462

返回顶部