webdriver笔记

  一、打开浏览器

 1谷歌

System.setProperty("webdriver.chrome.driver","C:/Program Files/Chrome/chromedriver.exe");ChromeOptions options = newChromeOptions();dr =newChromeDriver(options);dr.manage().window().maximize();//窗口最大化

 2.火狐

System.setProperty("webdriver.firefox.bin","C:/ProgramFiles/MozillaFirefox /firefox.exe");ProfilesIni pi =newProfilesIni();FirefoxProfile profile =pi.getprofile("default");dr =newFirefoxDriver(profile);

 3.IE

System.setProperty("webdriver.ie.driver","C:/ProgramFiles/InternetExplorer /IEDriverServer.exe ");DesiredCapabilities ieCapailities = DesiredCapabilities.interExplorer();dr =newInternetExplorerDriver(ieCapabilities);

二、鼠标操作:

1.鼠标右键: 

Actions action =newActions(dr); action.contextClick(dr.finElement(By.id(id))).perform();//perform不能少,不然右键没有用。

2.鼠标拖拽

WebElement source = dr.finElement(By.id(id));WebElement target= dr.finElement(By.id(id));newActions(dr).dragAndDrop(source,target).perform();

3.鼠标按下Enter/ Tab键

Actions action=newActions(driver);action.sendKeys(Keys.ENTER);action.sendKeys(Keys.Tab);action.sendKeys(Keys.NULL);

4.鼠标滚动

将滚动条滚动到目标对象出现

WebElement target = driver.findElement(By.id(elementId));((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", target);

4.修饰键方法:

Actions action=newActions(dr);actionkeyDown(Keys.CONTROL);//按下Ctrl键actionkeyDown(Keys.SHIFT);//按下Shift键actionkeyDown(Keys.ALT);//按下Alt键actionkeyUP(Keys.CONTROL);//释放Ctrl键

三、切换窗口

1.String currentwin =dr.getWindowHandle();Set wins= dr.getWindowHandles();for(Stringnewin:wins){if(newin.equals(currentwin))continue;else{dr.switchTo().window(newin);system.out.println(dr.getTitle());}}

四、遍历frame,切换到当前需要的frame

Listmyframes=dr.findElements(By.tagName("frame"));for(WebElement myframe:myframes) { myframe.getLocation(); } WebElement s=myframes.get(1); dr.switchTo().frame(s)

五、处理alert、confirm弹窗

alert弹窗,并输入

Alert Login =dr.switchTo().alert();Login.sendKeys("admin");Login.accept();dr.switchTo().defaultContent();

comfirm弹窗

Alert confirm=dr.switchTo().alert();confirm.accept();//确定confirm.dismiss();//取消

六、断言

WebElementcheck=dr.findElenment(By.id("id"));accsertTrue(check.getText().contains("不能大于100天"));

七、元素定位

xpath定位:

dr.findElement(By.xpath("(//input[@id='xx']//span[type='xx'])[1]")).click()

xpath结合逻辑定位

By.xpath("//input[@type='name' and@name='kw1']")

xpath部分属性值匹配

By.xpath("//input[start-with(@id,'nice')

By.xpath("//input[ends-with(@id,'很漂亮')

By.xpath("//input[contains(@id,'那么美')]")

css定位(对下拉框的操作):

new Select(dr.findElement(By.cssSelecor("select.select"))).selecrByVisibleText("xx");

八、截图方法

public void Screenshot()

{

int ran=(int) (Math.random()*100);

        Stringname="name"+ran+"";

try{

File srcFile=((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);

FileUtile.copyFile

(srcFile,newFile("G:\\NEW\\"+name+".png"));

}

catch(Exception e)

{

e.printStackTrace();

}

}

你可能感兴趣的:(webdriver笔记)