Selenium使用要點記錄
1.selenium處理下拉列表的各種方法
a.通過option元素里面的value屬性值選中
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元素顯示值選中
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開始)選中
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.來個下拉列表選中多個選項的情況
/** * @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.元素拖拽,感覺在自動化測試里邊這種需求比較少,但是我還是碰到了的哈
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放下拖動一個像素。
大家稍微去看看Actions類里邊還能發現很多關于元素操作的方法,希望你可能在里邊能找到解決你需求的方法。
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!