1.元素定位
--通过id定位元素 driver.findElement(By.id(“id的值”)); --name定位 driver.findElement(By.name(“name的值”)); --css方式定位 driver.findElement(By.cssSelector(“css表达式”)); --xpath定位 driver.findElement(By.xpath(“xpath表达式”)); --class名称定位 driver.findElement(By.className(“class属性”)); --链接定位 driver.findElement(By.linkText(“链接的全部文字”));
2.元素操作
输入框元素操作 // 在输入框中输入内容 element.sendKeys("test111111"); // 清空输入框 element.clear(); // 获取输入框的内容 element.getAttribute("value");
btn操作 // 点击按钮 addButton.click(); // 判断按钮是否enable addButton.isEnabled();
//下拉选择框的操作,index从0开始 select.selectByIndex(2); select.selectByValue("18"); select.selectByVisibleText("种类AA");
//截图
截图有三种方法
1.第一种是通过截图类TakeScreenshout实现截图
这种截图不包含导航栏
核心代码:
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //通过FileUtils中的copyFile()方法保存getScreenshotAs()返回的文件;"屏幕截图"即时保存截图的文件夹 try { FileUtils.copyFile(srcFile, new File("/Users/xxx/Downloads/截图.jpg")); } catch (IOException e) { e.printStackTrace(); }
2.第二种是通过Robot对象截屏
这种截取浏览器窗体内的内容及浏览器的菜单和桌面的任务栏区域
核心代码如下:
BufferedImage img = null; try { img = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); ImageIO.write(img, "jpg", new File("/Users/xxx/Downloads/截图.jpg")); } catch (AWTException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }
第三种方法是截图目标区域
WebElement element = driver.findElement(By.cssSelector("[width='180px']")); try { FileUtils.copyFile(captureElement(element), new File("/Users/xxx/Downloads/截图.jpg")); } catch (Exception e) { e.printStackTrace(); }