继续很不负责任的接上回,前一篇文章里边提到了selenium处理popup window和等待加载的scenario.java
今天继续讨论一个使用selenium很容易遇到的问题和一个很不经常使用的问题,好吧,开始讲起:测试
1.selenium处理下拉列表的各类方法ui
a.经过option元素里面的value属性值选中this
public void selectOptionByValue(WebElement select, String value, WebDriver driver) { //select = driver.findElement(By.id("id of select element")): List<WebElement> allOptions = select.findElements(By .tagName("option")); for (WebElement option : allOptions) { if (value.equals(option.getAttribute("value"))) { option.click(); break; } } }
b.经过option元素显示值选中google
public void selectOptionByVisibleText(String elementId, String visibleText){ WebElement ele = driver.findElement(By.id(elementId)); Select select = new Select(ele); select.selectByVisibleText(visibleText); }
c.经过opton在select中的index(从0开始)选中code
public void selectOptionByIndex(By by, String index){ try{ int ind = Integer.parseInt(index); WebElement ele = driver.findElement(by); this.selectOptionByIndex(ele, ind); }catch(Exception e){ loggerContxt.error(String.format("Please configure a numeric as the index of the optioin for %s..",by.toString())); return; } }
d.来个下拉列表选中多个选项的状况orm
/** * @elementId id of the select element * @param periodArr is the array of the indexes of the options in the dropdown list. */ public void selectMultipleOptionsInDropdownList(String elementId, String[] periodArr){ //你们自行传入这个driver对象 Actions actions = new Actions(this.driver); //我这里单个的option选中是用的option的index经过xpath的方式定位的,你们能够尝试上边其余的方式 for (int i = 0; i < periodArr.length; i++) { try{ int num = Integer.parseInt(periodArr[i]); WebElement ele = driver.findElement( By.xpath(String.format(".//select[@id='%s']/option[%d]",elementId,num))); actions.moveToElement(ele); if (!ele.isSelected()) { actions.click(); } }catch(Exception e){ loggerContxt.info(String.format("Failed to parse the radia count::%s for Quater peroid.",periodArr[i])); continue; } } actions.perform();
暂时就列这么些关于下拉列表的处理吧,这个挺好google,实在想偷懒的能够给我留言。
对象
2.元素拖拽,感受在自动化测试里边这种需求比较少,可是我仍是碰到了的哈ip
WebElement element1 = driver.findElement(By.id("element1")); WebElement element2 = driver.findElement(By.id("element2")); Actions actions = new Actions(driver); //选中须要拖动的元素,而且往x,y方向拖动一个像素的距离,这样元素就被鼠标拉出来了,而且hold住 actions.clickAndHold(element1).moveByOffset(1, 1); //把选中的元素拉倒目的元素上方,而且释放鼠标左键让需拖动元素释放下去 actions.moveToElement(element2).release(); //组织完这些一系列的步骤,而后开始真实执行操做 Action action = actions.build(); action.perform();
其实Actions里边有public Actions dragAndDrop(WebElement source, WebElement target)这个方法能直接去拖拽元素,可能个人界面有点不太规范,用官方提供的这个一直不成功,因此我在这一系列的子操做之间加了一个小的步骤:选中source element以后往x,y放下拖动一个像素。element
你们稍微去看看Actions类里边还能发现不少关于元素操做的方法,但愿你可能在里边能找到解决你需求的方法。