下面列出了org.openqa.selenium.Dimension#getWidth ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @param direction
* @param startPosition
* @param distancePercent
* @param setting
* @param screenSize
* @param elementSize
* @param elementLocation
* @param actions
* @return action
* @author wasiq.bhamla
* @since Sep 18, 2018 8:03:55 PM
*/
public static <T extends TouchAction<T>> T swipeTo(final SwipeDirection direction,
final SwipeStartPosition startPosition, final int distancePercent, final PlaybackSetting setting,
final Dimension screenSize, final Dimension elementSize, final Point elementLocation, final T actions) {
final double distance = distancePercent / 100.0;
final Point source = getStartPoint(startPosition, screenSize, elementSize, elementLocation);
int endX = source.getX() + (int) (source.getX() * direction.getX() * distance);
int endY = source.getY() + (int) (source.getY() * direction.getY() * distance);
if (elementSize != null) {
endX = source.getX() + (int) (elementSize.getWidth() * direction.getX() * distance);
endY = source.getY() + (int) (elementSize.getHeight() * direction.getY() * distance);
}
return actions.press(PointOption.point(source.getX(), source.getY()))
.waitAction(WaitOptions.waitOptions(Duration.ofMillis(setting.getDelayBeforeSwipe())))
.moveTo(PointOption.point(endX, endY))
.release();
}
public void get( String url )
{
setLastAction();
webDriver.get( url );
try
{
double outerHeight = Integer.parseInt( executeScript( "return window.outerHeight;" ) + "" );
double outerWidth = Integer.parseInt( executeScript( "return window.outerWidth;" ) + "" );
Dimension windowSize = manage().window().getSize();
Object f = executeScript( "return window.outerHeight;" );
heightModifier = (double) windowSize.getHeight() / outerHeight;
widthModifier = (double) windowSize.getWidth() / outerWidth;
}
catch( Exception e )
{
log.warn( "Could not extract height/width modifiers" );
heightModifier = 1;
widthModifier = 1;
}
}
private void clickAt( WebElement webElement, WebDriver webDriver, int x, int y )
{
if ( webElement != null )
{
Dimension elementSize = webElement.getSize();
int useX = (int) ((double) elementSize.getWidth() * ((double) x / 100.0)) + webElement.getLocation().getX();
int useY = (int) ((double) elementSize.getHeight() * ((double) y / 100.0)) + webElement.getLocation().getY();
if ( ((DeviceWebDriver) webDriver).getNativeDriver() instanceof AppiumDriver )
{
new TouchAction( (AppiumDriver) ((DeviceWebDriver) webDriver).getNativeDriver() ).press( PointOption.point( useX, useY ) ).perform();
}
else if ( ((DeviceWebDriver) webDriver).getNativeDriver() instanceof RemoteWebDriver )
{
if ( ((DeviceWebDriver) webDriver).getNativeDriver() instanceof HasTouchScreen )
new TouchActions( webDriver ).move( useX, useY ).click().build().perform();
else
new Actions( webDriver ).moveByOffset(useX, useY ).click().build().perform();
}
}
}
@Test
public void listenResizeEvent() {
open();
if (hasClientUnknownIssue()) {
return;
}
Dimension currentSize = getDriver().manage().window().getSize();
int newWidth = currentSize.getWidth() - 10;
getDriver().manage().window()
.setSize(new Dimension(newWidth, currentSize.getHeight()));
WebElement info = findElement(By.id("size-info"));
Assert.assertEquals(String.valueOf(newWidth), info.getText());
newWidth -= 30;
getDriver().manage().window()
.setSize(new Dimension(newWidth, currentSize.getHeight()));
Assert.assertEquals(String.valueOf(newWidth), info.getText());
}
/**
* Performs the lo touch gesture according to the point coordinates.
*
* @param locator
* write in format of x,y. can be in pixels or
* percentage(recommended) for example 50%,50%.
*/
@Then("^I tap on \"(.*?)\" for \"(\\d*\\.?\\d*)\" seconds$")
public static void tapElement(String locator, int seconds) {
QAFExtendedWebElement myElement = new QAFExtendedWebElement(locator);
Point location = myElement.getLocation();
Dimension size = myElement.getSize();
// determine location to click and convert to an appropriate string
int xToClick = location.getX() + (size.getWidth() / 2);
int yToClick = location.getY() + (size.getHeight() / 2);
String clickLocation = xToClick + "," + yToClick;
DeviceUtils.longTouch(clickLocation, seconds);
}
private int getWindowSize(String windowHandle)
{
WebDriver driver = getWebDriver();
driver.switchTo().window(windowHandle);
Dimension dimension = driver.manage().window().getSize();
return dimension.getHeight() * dimension.getWidth();
}
@Override
public void hover(Element ele)
{
WebElement webEle = searchStrategyUtils.findStrategy(WebElement.class, ele).search(ele);
if(webEle == null)
{
logger.warn("can not found element.");
return;
}
if(!(ele instanceof FileUpload))
{
Dimension size = webEle.getSize();
Point loc = webEle.getLocation();
int toolbarHeight = engine.getToolbarHeight();
int x = size.getWidth() / 2 + loc.getX();
int y = size.getHeight() / 2 + loc.getY() + toolbarHeight;
try
{
new Robot().mouseMove(x, y);
}
catch (AWTException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 参数初始化
*/
protected void initParameters() {
Dimension dimension;
// 兼容循环执行时,如果sessionId为空,则重新启动
if (DriverFactory.getInstance().getDriver().getSessionId() == null) {
DriverFactory.setDf(null);
}
dimension = DriverFactory.getInstance().getDriver().manage().window().getSize();
Constant.SCREEN_WIDTH = dimension.getWidth();
Constant.SCREEN_HEIGHT = dimension.getHeight();
LogUtil.info("界面宽高:" + Constant.SCREEN_WIDTH + "x" + Constant.SCREEN_HEIGHT);
}
private static Point getStartPoint(final SwipeStartPosition start, final Dimension screenSize,
final Dimension elementSize, final Point elementLocation) {
int x = 0;
int y = 0;
int width = screenSize.getWidth();
int height = screenSize.getHeight();
Point location = new Point(0, 0);
if (elementSize != null) {
width = elementSize.getWidth();
height = elementSize.getHeight();
location = elementLocation;
}
switch (start) {
case BOTTOM:
x = width / 2;
y = elementSize != null && height + location.getY() < screenSize.getHeight() ? height : height - 5;
break;
case CENTER:
x = width / 2;
y = height / 2;
break;
case LEFT:
x = elementSize != null && width + location.getX() > 0 ? 0 : 5;
y = height / 2;
break;
case RIGHT:
x = elementSize != null && width + location.getX() < screenSize.getWidth() ? width : width - 5;
y = height / 2;
break;
case TOP:
default:
x = width / 2;
y = 5;
break;
}
return new Point(location.getX() + x, location.getY() + y);
}
/**
* Gets the actual point.
*
* @param percentagePoint the percentage point
* @param screenDimension the screen dimension
* @return the actual point
*/
protected Point getActualPoint( Point percentagePoint, Dimension screenDimension )
{
if ( webElement != null )
{
if ( webElement.getLocation() != null && webElement.getSize() != null && webElement.getSize().getWidth() > 0 && webElement.getSize().getHeight() > 0 )
{
int x = percentagePoint.getX() * webElement.getSize().getWidth() + webElement.getLocation().getX();
int y = percentagePoint.getY() * webElement.getSize().getHeight() + webElement.getLocation().getY();
return new Point( x, y );
}
}
return new Point( (int) ( (percentagePoint.getX() / 100.0 ) * (double)screenDimension.getWidth() ), (int) ( (percentagePoint.getY() / 100.0 ) * (double)screenDimension.getHeight() ) );
}
public boolean _clickAt( int offsetX, int offsetY )
{
WebElement webElement = getElement();
if (webElement != null)
{
CloudActionProvider aP = getWebDriver().getCloud().getCloudActionProvider();
Dimension elementSize = aP.translateDimension(getWebDriver(), webElement.getSize());
int useX = (int) ((double) elementSize.getWidth() * ((double) offsetX / 100.0) + webElement.getLocation().getX());
int useY = (int) ((double) elementSize.getHeight() * ((double) offsetY / 100.0) + webElement.getLocation().getY());
if (log.isInfoEnabled())
log.info("Clicking " + useX + "," + useY + " pixels relative to " + getName());
if (getWebDriver() instanceof HasInputDevices)
{
if (isTimed())
getActionProvider().startTimer((DeviceWebDriver) getWebDriver(), this, getExecutionContext());
aP.tap(getWebDriver(), new PercentagePoint(useX, useY, false), 500);
return true;
}
return true;
}
return false;
}
public Coordinates(WebElement element, Double devicePixelRatio) {
Point point = element.getLocation();
Dimension size = element.getSize();
this.width = (int)(size.getWidth()*devicePixelRatio);
this.height = (int)(size.getHeight()*devicePixelRatio);
this.x = (int)(point.getX()*devicePixelRatio);
this.y = (int)(point.getY()*devicePixelRatio);
}
private void copyTerminalTextToClipboard(int terminalIndex) {
Dimension textLayerSize = getTextLayer(terminalIndex).getSize();
final Actions action = seleniumWebDriverHelper.getAction();
final int xBeginCoordinateShift = -(textLayerSize.getWidth() / 2);
final int yBeginCoordinateShift = -(textLayerSize.getHeight() / 2);
seleniumWebDriverHelper.moveCursorTo(getTextLayer(terminalIndex));
// shift to top left corner
seleniumWebDriverHelper
.getAction()
.moveByOffset(xBeginCoordinateShift, yBeginCoordinateShift)
.perform();
// select all terminal area by mouse
action.clickAndHold().perform();
seleniumWebDriverHelper
.getAction()
.moveByOffset(textLayerSize.getWidth(), textLayerSize.getHeight())
.perform();
action.release().perform();
// copy terminal output to clipboard
String keysCombination = Keys.chord(CONTROL, INSERT);
seleniumWebDriverHelper.sendKeys(keysCombination);
// cancel terminal area selection
clickOnTerminal(terminalIndex);
}
@Override
protected MobileDevice initMobile(IDevice iDevice, AppiumServer appiumServer) throws Exception {
String mobileId = iDevice.getSerialNumber();
boolean isRealDevice = !iDevice.isEmulator();
Mobile mobile = new Mobile();
mobile.setPlatform(MobileDevice.PLATFORM_IOS);
mobile.setCreateTime(new Date());
mobile.setId(mobileId);
mobile.setName(IosUtil.getDeviceName(mobileId, isRealDevice));
mobile.setEmulator(isRealDevice ? Mobile.REAL_MOBILE : Mobile.EMULATOR);
if (isRealDevice) {
mobile.setSystemVersion(IosUtil.getRealDeviceSystemVersion(mobileId));
}
IosDevice iosDevice = new IosDevice(mobile, appiumServer);
log.info("[{}]开始初始化appium", mobileId);
RemoteWebDriver driver = iosDevice.freshDriver(null, true);
log.info("[{}]初始化appium完成", mobileId);
if (!isRealDevice) {
try {
AppiumDriver appiumDriver = (AppiumDriver) driver;
String sdkVersion = (String) appiumDriver.getSessionDetail("sdkVersion");
mobile.setSystemVersion(sdkVersion);
} catch (Exception e) {
log.warn("[{}]获取sdkVersion失败", mobileId, e);
}
}
// 有时window获取的宽高可能为0
while (true) {
Dimension window = driver.manage().window().getSize();
int width = window.getWidth();
int height = window.getHeight();
if (width > 0 && height > 0) {
mobile.setScreenWidth(width);
mobile.setScreenHeight(height);
break;
} else {
log.warn("[{}]未获取到正确的屏幕宽高: {}", mobileId, window);
}
}
// 截图并上传到服务器
UploadFile uploadFile = iosDevice.screenshotThenUploadToServer();
mobile.setImgPath(uploadFile.getFilePath());
driver.quit();
return iosDevice;
}
protected Point center(WebElement webElement) {
Point location = webElement.getLocation();
Dimension size = webElement.getSize();
return new Point(location.getX() + size.getWidth() / 2, location.getY() + size.getHeight() / 2);
}
@Override
public Point translatePoint(DeviceWebDriver webDriver, Point currentPoint )
{
log.error( "Translating potin from " + currentPoint );
if ( deviceWidth == 0 || deviceHeight == 0 )
{
if ( webDriver.getPopulatedDevice().getResolution() == null )
{
deviceWidth = -1;
deviceHeight = -1;
return currentPoint;
}
String[] deviceResolution = webDriver.getPopulatedDevice().getResolution().split( "x" );
if ( deviceResolution.length != 2 )
{
deviceWidth = -1;
deviceHeight = -1;
return currentPoint;
}
try
{
deviceWidth = Integer.parseInt( deviceResolution[ 0 ] );
deviceHeight = Integer.parseInt( deviceResolution[ 1 ] );
}
catch( Exception e )
{
}
log.error( "Resolution is " + deviceWidth + ", " + deviceHeight);
if ( deviceWidth == 0 || deviceHeight == 0 )
{
deviceWidth = -1;
deviceHeight = -1;
return currentPoint;
}
}
if ( deviceWidth == -1 || deviceHeight == -1 )
return currentPoint;
//
// If we are here then we have a resolution
//
Point returnValue = new Point( currentPoint.getX(), currentPoint.getY() );
Dimension wD = webDriver.manage().window().getSize();
if ( deviceWidth > wD.getWidth() )
returnValue.x = returnValue.x * ( deviceWidth / wD.getWidth() );
else if ( deviceWidth < wD.getWidth() )
returnValue.x = returnValue.x * ( wD.getWidth() / deviceWidth );
if ( deviceHeight > wD.getHeight() )
returnValue.y = returnValue.y * ( deviceHeight / wD.getHeight() );
else if ( deviceHeight < wD.getHeight() )
returnValue.y = returnValue.y * ( wD.getHeight() / deviceHeight );
log.error( "New Point " + returnValue );
return returnValue;
}
@Override
protected boolean _executeGesture( WebDriver webDriver )
{
String executionId = getExecutionId( webDriver );
String deviceName = getDeviceName( webDriver );
if ( executionId != null && deviceName != null )
{
if ( webElement != null )
{
CloudActionProvider aP = ( (DeviceWebDriver) webDriver ).getCloud().getCloudActionProvider();
Point at = aP.translatePoint( ( (DeviceWebDriver) webDriver), webElement.getLocation() );
Dimension size = aP.translateDimension( (DeviceWebDriver) webDriver, webElement.getSize() );
if ( at != null && size != null && size.getWidth() > 0 && size.getHeight() > 0 )
{
int x = getStartOne().getX() * size.getWidth() + at.getX();
int y = getStartOne().getY() * size.getHeight() + at.getY();
Point swipeStart = new Point( x, y );
x = getEndOne().getX() * size.getWidth() + at.getX();
y = getEndOne().getY() * size.getHeight() + at.getY();
Point swipeEnd = new Point( x, y );
PerfectoMobile.instance(( (DeviceWebDriver) webDriver ).getxFID() ).gestures().pinch( executionId, deviceName, new PercentagePoint( swipeStart.getX(), swipeStart.getY(), false ), new PercentagePoint( swipeEnd.getX(), swipeEnd.getY(), false ) );
return true;
}
else
{
log.warn( "A relative elements was specified however no size could be determined" );
return false;
}
}
PerfectoMobile.instance(( (DeviceWebDriver) webDriver ).getxFID() ).gestures().pinch( executionId, deviceName, new PercentagePoint( getStartOne().getX(), getStartOne().getY() ), new PercentagePoint( getEndOne().getX(), getEndOne().getY() ) );
return true;
}
else
return false;
}
public boolean _clickFor( int length )
{
WebElement webElement = getElement();
if (webElement != null && webElement.getSize().getHeight() > 0 && webElement.getSize().getWidth() > 0)
{
if (getWebDriver() instanceof HasInputDevices)
{
if (isTimed())
getActionProvider().startTimer((DeviceWebDriver) getWebDriver(), this, getExecutionContext());
if (((DeviceWebDriver) getWebDriver()).getNativeDriver() instanceof AppiumDriver)
{
new TouchAction((AppiumDriver<?>) ((DeviceWebDriver) getWebDriver()).getNativeDriver()).press(createPoint(webElement)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(length))).release().perform();
}
else if (((DeviceWebDriver) getWebDriver()).getNativeDriver() instanceof RemoteWebDriver)
{
CloudActionProvider aP = getWebDriver().getCloud().getCloudActionProvider();
Point clickLocation = aP.translatePoint(getWebDriver(), webElement.getLocation());
Dimension clickSize = aP.translateDimension(getWebDriver(), webElement.getSize());
Dimension windowSize = aP.translateDimension(getWebDriver(), getWebDriver().manage().window().getSize());
double x = clickLocation.getX() + (clickSize.getWidth() / 2);
double y = clickLocation.getY() + (clickSize.getHeight() / 2);
int percentX = (int) (x / windowSize.getWidth() * 100.0);
int percentY = (int) (y / windowSize.getHeight() * 100.0);
try
{
new TouchActions(getWebDriver()).longPress(webElement).build().perform();
}
catch (Exception e)
{
((DeviceWebDriver) getWebDriver()).getCloud().getCloudActionProvider().tap((DeviceWebDriver) getWebDriver(), new PercentagePoint(percentX, percentY, true), length);
}
}
return true;
}
}
return false;
}
public Coordinates(Point point, Dimension size, Double devicePixelRatio) {
this.width = (int)(size.getWidth()*devicePixelRatio);
this.height = (int)(size.getHeight()*devicePixelRatio);
this.x = (int)(point.getX()*devicePixelRatio);
this.y = (int)(point.getY()*devicePixelRatio);
}
/**
* height is multiplied because we must avoid the situation when, in fact, different parties will
* give the same sum for example 15 + 25 == 25 + 15, but 15 + 25*10000 != 25 + 15*10000
*
* @param dimension consist partial sizes
* @return partial sizes sum with shift
*/
private int getSizeHashCode(Dimension dimension) {
return dimension.getWidth() + (dimension.getHeight() * 10000);
}