新人新手,初次接觸selenium+Java自動化測試,試着分享點學習中的東西。
在做自動化的時候,有時會遇見圖形化校驗的問題,特別是現在大部分網站都加上了滑塊校驗,今天分享一下最簡單的滑塊校驗的處理;

這個滑塊的處理步驟:
1.先定位和滑塊控件的元素;
2.獲得滑塊滑動的距離,也就是滑塊目的地的坐標;
3.拖動滑塊。
1.定位滑塊控件,如下圖

定位外面的控件也行,定位里面小的那個也行
//外 WebElement sour = driver.findElement(By.cssSelector(".cpt-img-double-right")); //內 WebElement sour = driver.findElement(By.cssSelector(".cpt-drop-btn"));
2.獲得滑塊滑動的距離,也就是滑塊目的地的坐標,如下圖

滑塊的運動就是從A點走到B點或C點的位置,需要把B或C的坐標,得到即可,
以A點為原點,水平距離為X,垂直距離為Y
1 //整個拖拽框的控件元素 2 WebElement ele = driver.findElement(By.cssSelector(".cpt-bg-bar")); 3 //拖拽的寬度即x的距離 4 int x = ele.getSize().getWidth(); 5 //拖拽的高度即y的距離 6 int y = ele.getSize().getHeight(); 7
3.拖動滑塊
1 //拖拽的動作 2 Actions action = new Actions(driver); 3 action.dragAndDropBy(sour, x, y).perform();
附上完整代碼
1 package se_2019; 2 3 import org.openqa.selenium.By; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 import org.openqa.selenium.firefox.FirefoxDriver; 7 import org.openqa.selenium.interactions.Actions; 8 public class lianxi_191001 { 9 10 public static void main(String[] args) throws InterruptedException { 11 //建立驅動 12 System.setProperty("webdriver.gecko.driver", "C:\\Program Files\\Mozilla Firefox\\geckodriver.exe"); 13 WebDriver driver = new FirefoxDriver(); 14 //輸入網址 15 driver.get("https://passport.ctrip.com/user/login"); 16 //輸入賬號密碼並點擊登錄 17 driver.findElement(By.id("nloginname")).sendKeys("18519523213"); 18 driver.findElement(By.id("npwd")).sendKeys("1"); 19 driver.findElement(By.id("nsubmit")).click(); 20 Thread.sleep(3000); 21 //滑塊控件元素 22 //WebElement sour = driver.findElement(By.cssSelector(".cpt-img-double-right")); 23 WebElement sour = driver.findElement(By.cssSelector(".cpt-drop-btn")); 24 //整個拖拽框的控件元素 25 WebElement ele = driver.findElement(By.cssSelector(".cpt-bg-bar")); 26 //拖拽的寬度即x的距離 27 int x = ele.getSize().getWidth(); 28 System.out.println(ele.getSize().getWidth()); 29 //拖拽的高度即y的距離 30 int y = ele.getSize().getHeight(); 31 System.out.println(ele.getSize().getHeight()); 32 Thread.sleep(3000); 33 //拖拽的動作 34 Actions action = new Actions(driver); 35 action.dragAndDropBy(sour, x, y).perform(); 36 Thread.sleep(2000); 37 //關閉窗口 38 driver.close(); 39 40 } 41 42 }
