新人新手,初次接触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 = newActions(driver);3 action.dragAndDropBy(sour, x, y).perform();
附上完整代码
1 packagese_2019;2
3 importorg.openqa.selenium.By;4 importorg.openqa.selenium.WebDriver;5 importorg.openqa.selenium.WebElement;6 importorg.openqa.selenium.firefox.FirefoxDriver;7 importorg.openqa.selenium.interactions.Actions;8 public classlianxi_191001 {9
10 public static void main(String[] args) throwsInterruptedException {11 //建立驱动
12 System.setProperty("webdriver.gecko.driver", "C:\\Program Files\\Mozilla Firefox\\geckodriver.exe");13 WebDriver driver = newFirefoxDriver();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 = newActions(driver);35 action.dragAndDropBy(sour, x, y).perform();36 Thread.sleep(2000);37 //关闭窗口
38 driver.close();39
40 }41
42 }