webdriver学习

这个博客详细介绍了如何使用Webdriver进行网页自动化测试。涵盖了从启动不同浏览器,元素定位,交互操作,处理弹窗,选择框操作,以及使用Firefox配置等各个方面。示例代码主要针对Firefox,包括设置自定义路径,使用不同方法打开Firefox,以及处理frame、alert和cookie等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package webdriver;


import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.Cookie.Builder;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;


import com.opera.core.systems.OperaSettings.Capability;
import com.thoughtworks.selenium.Selenium;


public class OpenBrowsers {
public static void main(String[] args) {
// 打开默认的firefox
// WebDriver driver = new FirefoxDriver();
// 打开指定路径的firefox 方法1
System.setProperty("webdriver.firefox.bin", "D:\\firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();


// 打开指定路径的firefox 方法2
// File pathToFirefoxBinary = new File("D:\\firefox\\firefox.exe");
// FirefoxBinary firefoxbin= new FirefoxBinary(pathToFirefoxBinary);
// WebDriver driverFireFox1=new FirefoxDriver(firefoxbin,null);
/*
* //打开ie WebDriver ie=new InternetExplorerDriver(); //chrome
* System.setProperty("webdriver.chrome.driver", "D:\\chrome.exe");
* System.setProperty("webdriver.chrome.bin",
* "D:\\360jisu\\360Chrome\\Chrome\\Application\\360chrome.exe");
*/
// driver.get(url);
// driver.quit();
// driver.close();
/*
* driver.getTitle(); driver.getCurrentUrl();
* System.out.println("title"+"\n"+driver.getTitle());
* driver.getWindowHandle();//当前浏览器的窗口句柄
* driver.getWindowHandles();//当前浏览器的所有窗口句柄
* driver.getPageSource();//当前页面源码
*//**
* 执行js
*/
/*// ((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a test\")");


// 元素定位
driver.get("http://www.51.com");


WebElement element = driver.findElement(By.className("login clear"));
System.out.println(element.getTagName());


// findElements,找到所有input对象
List<WebElement> element1 = driver.findElements(By.tagName("input"));
for (WebElement webElement : element1) {
System.out.println(webElement.getAttribute("id"));
}


// 层级定位
WebElement classelement = driver.findElement(By.className("login"));
List<WebElement> element2 = driver.findElements(By.tagName("label"));
for (WebElement webElement : element2) {
System.out.println(webElement.getText());
}


// 定位frame
driver.findElement(By.id("id1"));
切换到frame中 
driver.switchTo().frame("frame");
driver.findElement(By.id("div1"));
driver.findElement(By.id("input1"));
返回default content 
driver.switchTo().defaultContent();
driver.findElement(By.id("id1"));
// 获得新窗口
获得当前窗口句柄 
String currentWindow = driver.getWindowHandle();
// 得到所有窗口句柄
Set<String> handls = driver.getWindowHandles();
Iterator<String> it = handls.iterator();
while (it.hasNext()) {
if (currentWindow == it.next())
continue;
WebDriver window = driver.switchTo().window(it.next());
System.out.println("title,url=" + window.getTitle() + ","
+ window.getCurrentUrl());
}
// 返回之前的窗口
WebDriver window = driver.switchTo().window(currentWindow);
*/
/* //alert窗口1
driver.findElement(By.id("alert")).click();
Alert alert=driver.switchTo().alert();//切换窗口到alert
String text=alert.getText();
System.out.println(text);
alert.dismiss();//关闭alert窗口
//confirm窗口2,确定按钮
driver.findElement(By.id("confirm")).click();
Alert confirm= driver.switchTo().alert();
String text1=confirm.getText();
System.out.println(text1);
confirm.accept();//点击确定按钮
//警告窗口
driver.findElement(By.id("prompt")).click();
Alert prompt= driver.switchTo().alert();
String text2=confirm.getText();
System.out.println(text2);
prompt.sendKeys("jarvi");
prompt.accept();
//select选项框,索引
Select selectAge=new Select(driver.findElement(By.id("User_Age")));
selectAge.selectByIndex(2);
//select选项框,value属性
Select selectShen=new Select(driver.findElement(By.id("User_Shen")));
selectShen.selectByValue("上海");
//select选项框,通过可见文本
Select selectTown=new Select(driver.findElement(By.id("User_Town")));
selectTown.selectByVisibleText("浦东");
//遍历一下下拉列表所有选项,用click进行选中选项
Select selectCity=new Select(driver.findElement(By.id("User_City")));
for (WebElement e : selectCity.getOptions()) {
e.click();
}
//添加cookie
Cookie cookie= new Cookie("name", "vaule");
driver.manage().addCookie(cookie);
//获得当前页面下所有的cookie
Set<Cookie> cookies=driver.manage().getCookies();
for (Cookie c : cookies) {
c.getDomain();
c.getName();
c.getValue();
c.getExpiry();
c.getPath();
}
//删除cookie
driver.manage().deleteAllCookies();
driver.manage().deleteCookieNamed("name");
driver.manage().deleteCookie(cookie);

//元素拖拽
WebElement element = driver.findElement(By.id("item1"));
WebElement target = driver.findElement(By.id("drop"));
(new Actions(driver)).dragAndDrop(element, target).perform();


//显示等待页面元素加载完毕
WebDriverWait wait=new WebDriverWait(driver, 10);
wait.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver d) {
// TODO Auto-generated method stub
return d.findElement(By.id("b"));
}
}).click();
WebElement element2= driver.findElement(By.cssSelector(".red_box"));
((JavascriptExecutor)driver).executeScript("argument[0].style.border=\"5px solid yellow \"", element);
//隐形等待
//设置10秒
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
*/
/*
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File screenShotFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShotFile, new File("d:/test.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


//actions类各种操作
//单一操作
WebElement element=driver.findElement(By.id("test"));
WebElement element1=driver.findElement(By.id("test1"));
element.sendKeys("test");
element1.click();

Actions action= new Actions(driver);
WebElement element2 = driver.findElement(By.id("test"));
WebElement element3 = driver.findElement(By.id("su"));
action.sendKeys(element2,"test").perform();
action.click().perform();
//组合操作
(new Actions(driver)).dragAndDrop(driver.findElement(By.id("item")), element3).perform();
*/

/* //操作firefox profile
FirefoxProfile profile= new FirefoxProfile();
profile.setPreference("aaa", "bbbb");
WebDriver driver =new FirefoxDriver(profile);*/
/* //使用已存在的profile
ProfilesIni allprofiles= new ProfilesIni();
FirefoxProfile profile = allprofiles.getProfile("WebDriver");
WebDriver driver2 =new FirefoxDriver(profile);*/
//未注册的firefox profile
/*File profieDir= new File("path/to/your/profile");
FirefoxProfile profile= new FirefoxProfile(profieDir);
WebDriver driver2 =new FirefoxDriver(profile);
*/
//装在一个firefox插件
/* File file= new File("path/firebug-1.8.1.xpi");
FirefoxProfile profile= new FirefoxProfile(file);
try {
profile.addExtension(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
profile.setPreference("extensions.firebug.currentVersion", "1.8.1");
WebDriver driver2 =new FirefoxDriver(profile);

FirefoxProfile profile1=new FirefoxProfile();
*/ //profile1.setEnableNativeEvents(true);//启用被禁用的功能
//使用代理
/* String proxyString= "localhost:8888";
Proxy proxy= new Proxy();
proxy.setHttpProxy(proxyString);
proxy.setFtpProxy(proxyString);
proxy.setSslProxy(proxyString);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setPreference(CapabilityType.PROXY,proxy);
*/
package core;


import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver.Timeouts;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;


public class ActionDriverHelper {
protected WebDriver driver;
public ActionDriverHelper(WebDriver driver){
this.driver = driver ;
}


public void click(By by) {
driver.findElement(by).click();
}

public void doubleClick(By by){
new Actions(driver).doubleClick(driver.findElement(by)).perform();
}

public void contextMenu(By by) {
new Actions(driver).contextClick(driver.findElement(by)).perform();
}

public void clickAt(By by,String coordString) {
int index = coordString.trim().indexOf(',');
int xOffset = Integer.parseInt(coordString.trim().substring(0, index));
int yOffset = Integer.parseInt(coordString.trim().substring(index+1));
new Actions(driver).moveToElement(driver.findElement(by), xOffset, yOffset).click().perform();
}

public void doubleClickAt(By by,String coordString){
int index = coordString.trim().indexOf(',');
int xOffset = Integer.parseInt(coordString.trim().substring(0, index));
int yOffset = Integer.parseInt(coordString.trim().substring(index+1));
new Actions(driver).moveToElement(driver.findElement(by), xOffset, yOffset)
  .doubleClick(driver.findElement(by))
  .perform();
}

public void contextMenuAt(By by,String coordString) {
int index = coordString.trim().indexOf(',');
int xOffset = Integer.parseInt(coordString.trim().substring(0, index));
int yOffset = Integer.parseInt(coordString.trim().substring(index+1));
new Actions(driver).moveToElement(driver.findElement(by), xOffset, yOffset)
.contextClick(driver.findElement(by))
.perform();
}

public void fireEvent(By by,String eventName) {
System.out.println("webdriver 不建议使用这样的方法,所以没有实现。");
}

public void focus(By by) {
System.out.println("webdriver 不建议使用这样的方法,所以没有实现。");
}

public void keyPress(By by,Keys theKey) {
new Actions(driver).keyDown(driver.findElement(by), theKey).release().perform();
}

public void shiftKeyDown() {
new Actions(driver).keyDown(Keys.SHIFT).perform();
}

public void shiftKeyUp() {
new Actions(driver).keyUp(Keys.SHIFT).perform();
}

public void metaKeyDown() {
new Actions(driver).keyDown(Keys.META).perform();
}


public void metaKeyUp() {
new Actions(driver).keyUp(Keys.META).perform();
}


public void altKeyDown() {
new Actions(driver).keyDown(Keys.ALT).perform();
}


public void altKeyUp() {
new Actions(driver).keyUp(Keys.ALT).perform();
}


public void controlKeyDown() {
new Actions(driver).keyDown(Keys.CONTROL).perform();
}


public void controlKeyUp() {
new Actions(driver).keyUp(Keys.CONTROL).perform();
}

public void KeyDown(Keys theKey) {
new Actions(driver).keyDown(theKey).perform();
}
public void KeyDown(By by,Keys theKey){
new Actions(driver).keyDown(driver.findElement(by), theKey).perform();
}

public void KeyUp(Keys theKey){
new Actions(driver).keyUp(theKey).perform();
}

public void KeyUp(By by,Keys theKey){
new Actions(driver).keyUp(driver.findElement(by), theKey).perform();
}

public void mouseOver(By by) {
new Actions(driver).moveToElement(driver.findElement(by)).perform();
}

public void mouseOut(By by) {
System.out.println("没有实现!");
//new Actions(driver).moveToElement((driver.findElement(by)), -10, -10).perform();
}

public void mouseDown(By by) {
new Actions(driver).clickAndHold(driver.findElement(by)).perform();
}

public void mouseDownRight(By by) {
System.out.println("没有实现!");
}

public void mouseDownAt(By by,String coordString) {
System.out.println("没有实现!");
}


public void mouseDownRightAt(By by,String coordString) {
System.out.println("没有实现!");
}


public void mouseUp(By by) {
System.out.println("没有实现!");
}


public void mouseUpRight(By by) {
System.out.println("没有实现!");
}


public void mouseUpAt(By by,String coordString) {
System.out.println("没有实现!");
}


public void mouseUpRightAt(By by,String coordString) {
System.out.println("没有实现!");
}


public void mouseMove(By by) {
new Actions(driver).moveToElement(driver.findElement(by)).perform();
}


public void mouseMoveAt(By by,String coordString) {
int index = coordString.trim().indexOf(',');
int xOffset = Integer.parseInt(coordString.trim().substring(0, index));
int yOffset = Integer.parseInt(coordString.trim().substring(index+1));
new Actions(driver).moveToElement(driver.findElement(by),xOffset,yOffset).perform();
}
public void type(By by, String testdata) {
driver.findElement(by).clear();
driver.findElement(by).sendKeys(testdata);
}


public void typeKeys(By by, Keys key) {
driver.findElement(by).sendKeys(key);
}
public void setSpeed(String value) {
    System.out.println("The methods to set the execution speed in WebDriver were deprecated");
}


public String getSpeed() {
System.out.println("The methods to set the execution speed in WebDriver were deprecated");
return null;

}
public void check(By by) {
if(!isChecked(by))
click(by);
}


public void uncheck(By by) {
if(isChecked(by)) 
click(by);
}

public void select(By by,String optionValue) {
new Select(driver.findElement(by)).selectByValue(optionValue);
}

public void select(By by,int index) {
new Select(driver.findElement(by)).selectByIndex(index);
}


public void addSelection(By by,String optionValue) {
select(by,optionValue);
}
public void addSelection(By by,int index) {
select(by,index);
}

public void removeSelection(By by,String value) {
new Select(driver.findElement(by)).deselectByValue(value);
}

public void removeSelection(By by,int index) {
new Select(driver.findElement(by)).deselectByIndex(index);
}


public void removeAllSelections(By by) {
new Select(driver.findElement(by)).deselectAll();
}

public void submit(By by) {
driver.findElement(by).submit();
}

public void open(String url) {
driver.get(url);
}

public void openWindow(String url,String handler) {
System.out.println("方法没有实现!");
}


public void selectWindow(String handler) {
driver.switchTo().window(handler);
}

public String getCurrentHandler(){
String currentHandler = driver.getWindowHandle();
return currentHandler;
}

public String getSecondWindowHandler(){
Set<String> handlers = driver.getWindowHandles();
String reHandler = getCurrentHandler();
for(String handler : handlers){
if(reHandler.equals(handler))  continue;
reHandler = handler;
}
return reHandler;
}

public void selectPopUp(String handler) {
driver.switchTo().window(handler);
}

public void selectPopUp() {
driver.switchTo().window(getSecondWindowHandler());
}

public void deselectPopUp() {
driver.switchTo().window(getCurrentHandler());
}

public void selectFrame(int index) {
driver.switchTo().frame(index);
}

public void selectFrame(String str) {
driver.switchTo().frame(str);
}

public void selectFrame(By by) {
driver.switchTo().frame(driver.findElement(by));
}
public void waitForPopUp(String windowID,String timeout) {
System.out.println("没有实现");
}
public void accept(){
driver.switchTo().alert().accept();
}
public void dismiss(){
driver.switchTo().alert().dismiss();
}
public void chooseCancelOnNextConfirmation() {
driver.switchTo().alert().dismiss();
}

public void chooseOkOnNextConfirmation() {
driver.switchTo().alert().accept();
}


public void answerOnNextPrompt(String answer) {
driver.switchTo().alert().sendKeys(answer);
}

public void goBack() {
driver.navigate().back();
}


public void refresh() {
driver.navigate().refresh();
}

public void forward() {
driver.navigate().forward();
}

public void to(String urlStr){
driver.navigate().to(urlStr);
}

public void close() {
driver.close();
}

public boolean isAlertPresent() {
Boolean b = true;
try{
driver.switchTo().alert();
}catch(Exception e){
b = false;
}
return b;
}


public boolean isPromptPresent() {
return isAlertPresent();
}


public boolean isConfirmationPresent() {
return isAlertPresent();
}


public String getAlert() {
return driver.switchTo().alert().getText();
}


public String getConfirmation() {
return getAlert();
}


public String getPrompt() {
return getAlert();
}


public String getLocation() {
return driver.getCurrentUrl();
}

public String getTitle(){
return driver.getTitle();
}

public String getBodyText() {
String str = "";
List<WebElement> elements = driver.findElements(By.xpath("//body//*[contains(text(),*)]"));
for(WebElement e : elements){
str += e.getText()+" ";
}
return str;
}


public String getValue(By by) {
return driver.findElement(by).getAttribute("value");
}


public String getText(By by) {
return driver.findElement(by).getText();
}


public void highlight(By by) {
WebElement element = driver.findElement(by);
((JavascriptExecutor)driver).executeScript("arguments[0].style.border = \"5px solid yellow\"",element); 
}


public Object getEval(String script,Object... args) {
return ((JavascriptExecutor)driver).executeScript(script,args);
}
public Object getAsyncEval(String script,Object... args){
return  ((JavascriptExecutor)driver).executeAsyncScript(script, args);
}
public boolean isChecked(By by) {
return driver.findElement(by).isSelected();
}
public String getTable(By by,String tableCellAddress) {
WebElement table = driver.findElement(by);
int index = tableCellAddress.trim().indexOf('.');
int row =  Integer.parseInt(tableCellAddress.substring(0, index));
int cell = Integer.parseInt(tableCellAddress.substring(index+1));
List<WebElement> rows = table.findElements(By.tagName("tr"));
WebElement theRow = rows.get(row);
String text = getCell(theRow, cell);
return text;
}
private String getCell(WebElement Row,int cell){
List<WebElement> cells;
String text = null;
if(Row.findElements(By.tagName("th")).size()>0){
cells = Row.findElements(By.tagName("th"));
text = cells.get(cell).getText();
}
if(Row.findElements(By.tagName("td")).size()>0){
cells = Row.findElements(By.tagName("td"));
text = cells.get(cell).getText();
}
return text;
 
}


public String[] getSelectedLabels(By by) {
Set<String> set = new HashSet<String>();
   List<WebElement> selectedOptions = new Select(driver.findElement(by))
    .getAllSelectedOptions();
   for(WebElement e : selectedOptions){
    set.add(e.getText());
   }
return set.toArray(new String[set.size()]);
}


public String getSelectedLabel(By by) {
return getSelectedOption(by).getText();
}


public String[] getSelectedValues(By by) {
Set<String> set = new HashSet<String>();
   List<WebElement> selectedOptions = new Select(driver.findElement(by))
    .getAllSelectedOptions();
   for(WebElement e : selectedOptions){
    set.add(e.getAttribute("value"));
   }
return set.toArray(new String[set.size()]);
}


public String getSelectedValue(By by) {
return getSelectedOption(by).getAttribute("value");
}


public String[] getSelectedIndexes(By by) {
Set<String> set = new HashSet<String>();
   List<WebElement> selectedOptions = new Select(driver.findElement(by))
    .getAllSelectedOptions();
  List<WebElement> options = new Select(driver.findElement(by)).getOptions();
   for(WebElement e : selectedOptions){
    set.add(String.valueOf(options.indexOf(e)));
   }
   return set.toArray(new String[set.size()]);
}


public String getSelectedIndex(By by) {
List<WebElement> options = new Select(driver.findElement(by)).getOptions();
return String.valueOf(options.indexOf(getSelectedOption(by)));
}


public String[] getSelectedIds(By by) {
Set<String> ids = new HashSet<String>();
List<WebElement> options = new Select(driver.findElement(by)).getOptions();
for(WebElement option : options){
if(option.isSelected()) {
ids.add(option.getAttribute("id")) ;
}
}
return ids.toArray(new String[ids.size()]);
}


public String getSelectedId(By by) {
return getSelectedOption(by).getAttribute("id");
}
private WebElement getSelectedOption(By by){
WebElement selectedOption = null;
List<WebElement> options = new Select(driver.findElement(by)).getOptions();
for(WebElement option : options){
if(option.isSelected()) {
selectedOption = option;
}
}
return selectedOption;
}

public boolean isSomethingSelected(By by) {
boolean b = false;
List<WebElement> options = new Select(driver.findElement(by)).getOptions();
for(WebElement option : options){
if(option.isSelected()) {
b = true ;
break;
}
}
return b;
}


public String[] getSelectOptions(By by) {
Set<String> set = new HashSet<String>();
   List<WebElement> options = new Select(driver.findElement(by)).getOptions();
   for(WebElement e : options){
    set.add(e.getText());
   }
return set.toArray(new String[set.size()]);
}
public String getAttribute(By by,String attributeLocator) {
return driver.findElement(by).getAttribute(attributeLocator);
}


public boolean isTextPresent(String pattern) {
String Xpath= "//*[contains(text(),\'"+pattern+"\')]" ;
try { 
driver.findElement(By.xpath(Xpath));
               return true; 
} catch (NoSuchElementException e) { 
               return false; 
}
}


public boolean isElementPresent(By by) {
return driver.findElements(by).size() > 0;
}


public boolean isVisible(By by) {
return driver.findElement(by).isDisplayed();
}


public boolean isEditable(By by) {
return driver.findElement(by).isEnabled();
}
public List<WebElement> getAllButtons() {
return driver.findElements(By.xpath("//input[@type='button']"));
}


public List<WebElement> getAllLinks() {
return driver.findElements(By.tagName("a"));
}


public List<WebElement> getAllFields() {
return driver.findElements(By.xpath("//input[@type='text']"));
}


public String[] getAttributeFromAllWindows(String attributeName) {
System.out.println("不知道怎么实现");
return null;
}
public void dragdrop(By by,String movementsString) {
dragAndDrop(by, movementsString);
}
public void dragAndDrop(By by,String movementsString) {
int index = movementsString.trim().indexOf('.');
int xOffset = Integer.parseInt(movementsString.substring(0, index));
int yOffset = Integer.parseInt(movementsString.substring(index+1));
new Actions(driver).clickAndHold(driver.findElement(by)).moveByOffset(xOffset, yOffset).perform();
}
public void setMouseSpeed(String pixels) {
System.out.println("不支持");
}


public Number getMouseSpeed() {
System.out.println("不支持");
return null;
}
public void dragAndDropToObject(By source,By target) {
new Actions(driver).dragAndDrop(driver.findElement(source), driver.findElement(target)).perform();
}


public void windowFocus() {
driver.switchTo().defaultContent();
}


public void windowMaximize() {
driver.manage().window().setPosition(new Point(0,0));
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Dimension dim = new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setSize(dim);
}


public String[] getAllWindowIds() {
System.out.println("不能实现!");
return null;
}


public String[] getAllWindowNames() {
System.out.println("不能实现!");
return null;
}


public String[] getAllWindowTitles() {
Set<String> handles = driver.getWindowHandles();
Set<String> titles = new HashSet<String>();
for(String handle : handles){
titles.add(driver.switchTo().window(handle).getTitle());
}
return titles.toArray(new String[titles.size()]);
}
public String getHtmlSource() {
return driver.getPageSource();
}


public void setCursorPosition(String locator,String position) {
System.out.println("没能实现!");
}


public Number getElementIndex(String locator) {
System.out.println("没能实现!");
return null;
}


public Object isOrdered(By by1,By by2) {
System.out.println("没能实现!");
return null;
}


public Number getElementPositionLeft(By by) {
return driver.findElement(by).getLocation().getX();
}


public Number getElementPositionTop(By by) {
return driver.findElement(by).getLocation().getY();
}


public Number getElementWidth(By by) {
return driver.findElement(by).getSize().getWidth();
}


public Number getElementHeight(By by) {
return driver.findElement(by).getSize().getHeight();
}


public Number getCursorPosition(String locator) {
System.out.println("没能实现!");
return null;
}


public String getExpression(String expression) {
System.out.println("没能实现!");
return null;
}


public Number getXpathCount(By xpath) {
return driver.findElements(xpath).size();
}


public void assignId(By by,String identifier) {
System.out.println("不想实现!");
}


/*public void allowNativeXpath(String allow) {
commandProcessor.doCommand("allowNativeXpath", new String[] {allow,});
}*/


/*public void ignoreAttributesWithoutValue(String ignore) {
commandProcessor.doCommand("ignoreAttributesWithoutValue", new String[] {ignore,});

}*/


public void waitForCondition(String script,String timeout,Object... args) {
Boolean b = false;
int time = 0;
while(time <= Integer.parseInt(timeout)){
b = (Boolean) ((JavascriptExecutor)driver).executeScript(script,args);
if(b==true) break;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
time += 1000;
}
}


public void setTimeout(String timeout) {
driver.manage().timeouts().implicitlyWait(Integer.parseInt(timeout), TimeUnit.SECONDS);
}


public void waitForPageToLoad(String timeout) {
driver.manage().timeouts().pageLoadTimeout(Integer.parseInt(timeout), TimeUnit.SECONDS);
}


public void waitForFrameToLoad(String frameAddress,String timeout) {
/*driver.switchTo().frame(frameAddress)
.manage()
.timeouts()
.pageLoadTimeout(Integer.parseInt(timeout), TimeUnit.SECONDS);*/
}


public String getCookie() {
String cookies = "";
Set<Cookie> cookiesSet = driver.manage().getCookies();
for(Cookie c : cookiesSet){
cookies += c.getName()+"="+c.getValue()+";";
}
return cookies;
}


public String getCookieByName(String name) {
return driver.manage().getCookieNamed(name).getValue();
}


public boolean isCookiePresent(String name) {
boolean b = false ;
if(driver.manage().getCookieNamed(name) != null || driver.manage().getCookieNamed(name).equals(null))
b = true;
return b;
}


public void createCookie(Cookie c) {

driver.manage().addCookie(c);
}


public void deleteCookie(Cookie c) {
driver.manage().deleteCookie(c);
}


public void deleteAllVisibleCookies() {
driver.manage().getCookieNamed("fs").isSecure();
}


/*public void setBrowserLogLevel(String logLevel) {

}*/


/*public void runScript(String script) {
commandProcessor.doCommand("runScript", new String[] {script,});
}*/


/*public void addLocationStrategy(String strategyName,String functionDefinition) {
commandProcessor.doCommand("addLocationStrategy", new String[] {strategyName,functionDefinition,});
}*/


public void captureEntirePageScreenshot(String filename) {
File screenShotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShotFile, new File(filename));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


/*public void rollup(String rollupName,String kwargs) {
commandProcessor.doCommand("rollup", new String[] {rollupName,kwargs,});
}


public void addScript(String scriptContent,String scriptTagId) {
commandProcessor.doCommand("addScript", new String[] {scriptContent,scriptTagId,});
}


public void removeScript(String scriptTagId) {
commandProcessor.doCommand("removeScript", new String[] {scriptTagId,});
}


public void useXpathLibrary(String libraryName) {
commandProcessor.doCommand("useXpathLibrary", new String[] {libraryName,});
}


public void setContext(String context) {
commandProcessor.doCommand("setContext", new String[] {context,});
}*/


/*public void attachFile(String fieldLocator,String fileLocator) {
commandProcessor.doCommand("attachFile", new String[] {fieldLocator,fileLocator,});
}*/


/*public void captureScreenshot(String filename) {
commandProcessor.doCommand("captureScreenshot", new String[] {filename,});
}*/


public String captureScreenshotToString() {
String screen = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);
return screen;
}


  /* public String captureNetworkTraffic(String type) {
       return commandProcessor.getString("captureNetworkTraffic", new String[] {type});
   }
*/
   /*public void addCustomRequestHeader(String key, String value) {
       commandProcessor.getString("addCustomRequestHeader", new String[] {key, value});
   }*/


   /*public String captureEntirePageScreenshotToString(String kwargs) {
return commandProcessor.getString("captureEntirePageScreenshotToString", new String[] {kwargs,});
}*/


public void shutDown() {
driver.quit();
}


/*public String retrieveLastRemoteControlLogs() {
return commandProcessor.getString("retrieveLastRemoteControlLogs", new String[] {});
}*/


public void keyDownNative(Keys keycode) {
new Actions(driver).keyDown(keycode).perform();
}


public void keyUpNative(Keys keycode) {
new Actions(driver).keyUp(keycode).perform();
}


public void keyPressNative(String keycode) {
new Actions(driver).click().perform();
}



public void waitForElementPresent(By by) {
for(int i=0; i<60; i++) {
if (isElementPresent(by)) {
break;
} else {
try {
driver.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}



public void clickAndWaitForElementPresent(By by, By waitElement) {
click(by);
waitForElementPresent(waitElement);
}


public Boolean VeryTitle(String exception,String actual){
if(exception.equals(actual)) return true;
else return false;
}
}



}
}
1.1 selenium webdriver学习(一)------------快速开始 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 selenium webdriver学习(二)————对浏览器的简单操作 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 selenium webdriver学习(三)------------执行js脚本 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.4 selenium webdriver学习(四)------------定位页面元素 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.5 selenium webdriver学习(五)------------iframe的处理 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 1.6 selenium webdriver学习(六)------------如何得到弹出窗口 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 1.7 selenium webdriver学习(七)------------如何处理alert、confirm、prompt对话框 . . . . . . . . .24 1.8 selenium webdriver学习(八)------------如何操作select下拉框 . . . . . . . . . . . . . . . . . . . . . . . . .27 1.9 selenium webdriver学习(九)------------如何操作cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 1.10 selenium webdriver学习(十)------------如何把一个元素拖放到另一个元素里面 . . . . . . . . . . .31 1.11 selenium webdriver学习(十一)------------如何等待页面元素加载完成 . . . . . . . . . . . . . . . . . .33 1.12 selenium webdriver学习(十二)------------如何利用selenium-webdriver截图 . . . . . . . . . . . .38
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值