基本方法
一、基本方法介绍
以操控chrome浏览器为例,进入登录页
//new一个ChromeDriver对象
WebDriver webDriver = new ChromeDriver();
//最大化窗口
webDriver.manage().window().maximize();
//删除所有的cookies
webDriver.manage().deleteAllCookies();
//设置超时时间为10
webDriver.manage().timeouts().implicitlWait(10,TimeUnit.SECONDS);
//进入登录页面 get里的内容为网址
webDriver.get("http://localhost:8080/als8c-web");
查找元素
//by id
WebElement webElement = webDriver.findElement(By.id("account"));
//by name
WebElement webElement = webDriver.findElement(By.name("account"));
//by classname
WebElement webElement = webDriver.findElement(By.className("account"));
//by tagname
WebElement webElement = webDriver.findElement(By.tagName("div"));
//by css
//css方式定位很灵活 如定位 "class=ff" 的form下的span下的"id=in"input
WebElement webElement = webDriver.findElement(By.cssSelector("form.ff>span>input#in"));
//匹配div后同级的所有input
webElement = WebDriver.findElement(By.cssSelector("div+input"));
//查找form下第二个inpt标签元素
webElement = WebDriver.findElement(By.cssSelector("form>input:nth-child(2)"));
//by xpath 匹配所有的a标签
webElement = WebDriver.findElement(By.xpath("//a"));
//匹配title='保存'的a标签
webElement = WebDriver.findElement(By.xpath("//a[@title='保存']"));
下拉框元素选择
new Select(webDriver.findElement(By.id("REPAYTYPE"))).selectByIndex(1);//【--请选择--】后,第一个选项
new Select(webDriver.findElement(By.id("REPAYTYPE"))).selectByValue();//通过value
new Select(webDriver.findElement(By.id("REPAYTYPE"))).selectByVisibleText();//通过文本
切换iframe
//切换到最上层
webDriver.switchTo().defaultContent();
//切换到父iframe
webDriver.switchTo().parentFrame();
//切换到当前层指定的iframe层中
webDriver.switchTo().frame(webDriver.findElements(By.xpath("//div[@i='dialog']/table/tbody/tr/td/div/iframe")).get(0));
//三种参数
WebDriver frame(int index); //第几个
WebDriver frame(String nameOrId);//iframe的name或则id
WebDriver frame(WebElement frameElement);//定位元素