51Testing软件测试论坛
标题:
selenium webdriver学习 16 – 用selenium webdriver实现selenium RC中的类似的方法
[打印本页]
作者:
悠悠小仙仙
时间:
2017-7-18 14:24
标题:
selenium webdriver学习 16 – 用selenium webdriver实现selenium RC中的类似的方法
最近想总结一下学习selenium webdriver的情况,于是就想用selenium webdriver里面的方法来实现selenium RC中操作的一些方法。目前封装了一个ActionDriverHelper类,来实现RC中Selenium.java和 DefaultSelenium.java中的方法。有一些方法还没有实现,写的方法大多没有经过测试,仅供参考。代码如下:
CODE:
<font size="3">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 ;
}
publicvoid click(By by) {
driver.findElement(by).click();
}
publicvoid doubleClick(By by){
new Actions(driver).doubleClick(driver.findElement(by)).perform();
}
publicvoid contextMenu(By by) {
new Actions(driver).contextClick(driver.findElement(by)).perform();
}
publicvoid 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();
}
publicvoid 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();
}
publicvoid 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();
}
publicvoid fireEvent(By by,String eventName) {
System.out.println("webdriver 不建议使用这样的方法,所以没有实现。");
}
publicvoid focus(By by) {
System.out.println("webdriver 不建议使用这样的方法,所以没有实现。");
}
publicvoid keyPress(By by,Keys theKey) {
new Actions(driver).keyDown(driver.findElement(by), theKey).release().perform();
}
publicvoid shiftKeyDown() {
new Actions(driver).keyDown(Keys.SHIFT).perform();
}
publicvoid shiftKeyUp() {
new Actions(driver).keyUp(Keys.SHIFT).perform();
}
publicvoid metaKeyDown() {
new Actions(driver).keyDown(Keys.META).perform();
}
publicvoid metaKeyUp() {
new Actions(driver).keyUp(Keys.META).perform();
}
publicvoid altKeyDown() {
new Actions(driver).keyDown(Keys.ALT).perform();
}
publicvoid altKeyUp() {
new Actions(driver).keyUp(Keys.ALT).perform();
}
publicvoid controlKeyDown() {
new Actions(driver).keyDown(Keys.CONTROL).perform();
}
publicvoid controlKeyUp() {
new Actions(driver).keyUp(Keys.CONTROL).perform();
}
publicvoid KeyDown(Keys theKey) {
new Actions(driver).keyDown(theKey).perform();
}
publicvoid KeyDown(By by,Keys theKey){
new Actions(driver).keyDown(driver.findElement(by), theKey).perform();
}
publicvoid KeyUp(Keys theKey){
new Actions(driver).keyUp(theKey).perform();
}
publicvoid KeyUp(By by,Keys theKey){
new Actions(driver).keyUp(driver.findElement(by), theKey).perform();
}
publicvoid mouseOver(By by) {
new Actions(driver).moveToElement(driver.findElement(by)).perform();
}
publicvoid mouseOut(By by) {
System.out.println("没有实现!");
//new Actions(driver).moveToElement((driver.findElement(by)), -10, -10).perform();
}
publicvoid mouseDown(By by) {
new Actions(driver).clickAndHold(driver.findElement(by)).perform();
}
publicvoid mouseDownRight(By by) {
System.out.println("没有实现!");
}
publicvoid mouseDownAt(By by,String coordString) {
System.out.println("没有实现!");
}
publicvoid mouseDownRightAt(By by,String coordString) {
System.out.println("没有实现!");
}
publicvoid mouseUp(By by) {
System.out.println("没有实现!");
}
publicvoid mouseUpRight(By by) {
System.out.println("没有实现!");
}
publicvoid mouseUpAt(By by,String coordString) {
System.out.println("没有实现!");
}
publicvoid mouseUpRightAt(By by,String coordString) {
System.out.println("没有实现!");
}
publicvoid mouseMove(By by) {
new Actions(driver).moveToElement(driver.findElement(by)).perform();
}
publicvoid 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();
}
publicvoid type(By by, String testdata) {
driver.findElement(by).clear();
driver.findElement(by).sendKeys(testdata);
}
publicvoid typeKeys(By by, Keys key) {
driver.findElement(by).sendKeys(key);
}
publicvoid 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");
returnnull;
}
publicvoid check(By by) {
if(!isChecked(by))
click(by);
}
publicvoid uncheck(By by) {
if(isChecked(by))
click(by);
}
publicvoid select(By by,String optionValue) {
new Select(driver.findElement(by)).selectByValue(optionValue);
}
publicvoid select(By by,int index) {
new Select(driver.findElement(by)).selectByIndex(index);
}
publicvoid addSelection(By by,String optionValue) {
select(by,optionValue);
}
publicvoid addSelection(By by,int index) {
select(by,index);
}
publicvoid removeSelection(By by,String value) {
new Select(driver.findElement(by)).deselectByValue(value);
}
publicvoid removeSelection(By by,int index) {
new Select(driver.findElement(by)).deselectByIndex(index);
}
publicvoid removeAllSelections(By by) {
new Select(driver.findElement(by)).deselectAll();
}
publicvoid submit(By by) {
driver.findElement(by).submit();
}
publicvoid open(String url) {
driver.get(url);
}
publicvoid openWindow(String url,String handler) {
System.out.println("方法没有实现!");
}
publicvoid 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;
}
</font>
复制代码
作者:
悠悠小仙仙
时间:
2017-7-18 14:26
publicvoid selectPopUp(String handler) {
driver.switchTo().window(handler);
}
publicvoid selectPopUp() {
driver.switchTo().window(getSecondWindowHandler());
}
publicvoid deselectPopUp() {
driver.switchTo().window(getCurrentHandler());
}
publicvoid selectFrame(int index) {
driver.switchTo().frame(index);
}
publicvoid selectFrame(String str) {
driver.switchTo().frame(str);
}
publicvoid selectFrame(By by) {
driver.switchTo().frame(driver.findElement(by));
}
publicvoid waitForPopUp(String windowID,String timeout) {
System.out.println("没有实现");
}
publicvoid accept(){
driver.switchTo().alert().accept();
}
publicvoid dismiss(){
driver.switchTo().alert().dismiss();
}
publicvoid chooseCancelOnNextConfirmation() {
driver.switchTo().alert().dismiss();
}
publicvoid chooseOkOnNextConfirmation() {
driver.switchTo().alert().accept();
}
publicvoid answerOnNextPrompt(String answer) {
driver.switchTo().alert().sendKeys(answer);
}
publicvoid goBack() {
driver.navigate().back();
}
publicvoid refresh() {
driver.navigate().refresh();
}
publicvoid forward() {
driver.navigate().forward();
}
publicvoid to(String urlStr){
driver.navigate().to(urlStr);
}
publicvoid close() {
driver.close();
}
publicboolean isAlertPresent() {
Boolean b = true;
try{
driver.switchTo().alert();
}catch(Exception e){
b = false;
}
return b;
}
publicboolean isPromptPresent() {
return isAlertPresent();
}
publicboolean 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();
}
publicvoid 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);
}
publicboolean 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;
}
publicboolean 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);
}
publicboolean isTextPresent(String pattern) {
String Xpath= "//*[contains(text(),\'"+pattern+"\')]" ;
try {
driver.findElement(By.xpath(Xpath));
returntrue;
} catch (NoSuchElementException e) {
returnfalse;
}
}
publicboolean isElementPresent(By by) {
return driver.findElements(by).size() >0;
}
publicboolean isVisible(By by) {
return driver.findElement(by).isDisplayed();
}
publicboolean 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("不知道怎么实现");
returnnull;
}
publicvoid dragdrop(By by,String movementsString) {
dragAndDrop(by, movementsString);
}
publicvoid 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();
}
publicvoid setMouseSpeed(String pixels) {
System.out.println("不支持");
}
public Number getMouseSpeed() {
System.out.println("不支持");
returnnull;
}
publicvoid dragAndDropToObject(By source,By target) {
new Actions(driver).dragAndDrop(driver.findElement(source), driver.findElement(target)).perform();
}
publicvoid windowFocus() {
driver.switchTo().defaultContent();
}
publicvoid 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);
}
复制代码
作者:
悠悠小仙仙
时间:
2017-7-18 14:27
public String[] getAllWindowIds() {
System.out.println("不能实现!");
returnnull;
}
public String[] getAllWindowNames() {
System.out.println("不能实现!");
returnnull;
}
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();
}
publicvoid setCursorPosition(String locator,String position) {
System.out.println("没能实现!");
}
public Number getElementIndex(String locator) {
System.out.println("没能实现!");
returnnull;
}
public Object isOrdered(By by1,By by2) {
System.out.println("没能实现!");
returnnull;
}
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("没能实现!");
returnnull;
}
public String getExpression(String expression) {
System.out.println("没能实现!");
returnnull;
}
public Number getXpathCount(By xpath) {
return driver.findElements(xpath).size();
}
publicvoid assignId(By by,String identifier) {
System.out.println("不想实现!");
}
/*publicvoid allowNativeXpath(String allow) {
commandProcessor.doCommand("allowNativeXpath",new String[] {allow,});
}*/
/*public void ignoreAttributesWithoutValue(String ignore) {
commandProcessor.doCommand("ignoreAttributesWithoutValue", new String[] {ignore,});
}*/
publicvoid 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;
}
}
publicvoid setTimeout(String timeout) {
driver.manage().timeouts().implicitlyWait(Integer.parseInt(timeout), TimeUnit.SECONDS);
}
publicvoid waitForPageToLoad(String timeout) {
driver.manage().timeouts().pageLoadTimeout(Integer.parseInt(timeout), TimeUnit.SECONDS);
}
publicvoid 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();
}
publicboolean isCookiePresent(String name) {
boolean b =false ;
if(driver.manage().getCookieNamed(name) !=null || driver.manage().getCookieNamed(name).equals(null))
b = true;
return b;
}
publicvoid createCookie(Cookie c) {
driver.manage().addCookie(c);
}
publicvoid deleteCookie(Cookie c) {
driver.manage().deleteCookie(c);
}
publicvoid 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,});
}*/
publicvoid 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,});
}*/
publicvoid shutDown() {
driver.quit();
}
/*public String retrieveLastRemoteControlLogs() {
return commandProcessor.getString("retrieveLastRemoteControlLogs", new String[] {});
}*/
publicvoid keyDownNative(Keys keycode) {
new Actions(driver).keyDown(keycode).perform();
}
publicvoid keyUpNative(Keys keycode) {
new Actions(driver).keyUp(keycode).perform();
}
publicvoid keyPressNative(String keycode) {
new Actions(driver).click().perform();
}
publicvoid waitForElementPresent(By by) {
for(int i=0; i<60; i++) {
if (isElementPresent(by)) {
break;
} else {
try {
driver.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
publicvoid clickAndWaitForElementPresent(By by, By waitElement) {
click(by);
waitForElementPresent(waitElement);
}
public Boolean VeryTitle(String exception,String actual){
if(exception.equals(actual))returntrue;
elsereturnfalse;
}
}
复制代码
PS:有什么建议,欢迎评论,一起交流!
作者:
梦想家
时间:
2018-5-14 17:55
作者:
梦想家
时间:
2018-5-14 17:55
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/)
Powered by Discuz! X3.2