Example usage for org.openqa.selenium WebElement getLocation

List of usage examples for org.openqa.selenium WebElement getLocation

Introduction

In this page you can find the example usage for org.openqa.selenium WebElement getLocation.

Prototype

Point getLocation();

Source Link

Document

Where on the page is the top left-hand corner of the rendered element?

Usage

From source file:de.knowwe.uitest.PanelUITest.java

License:Open Source License

protected boolean isRightPanelVisible() {
    WebElement rightPanel;
    try {//from  w  ww .j  a  v a  2 s. co m
        rightPanel = getRightPanel();
    } catch (NoSuchElementException e) {
        return false;
    }
    int width = rightPanel.getSize().getWidth();
    int windowWidth = getDriver().manage().window().getSize().getWidth();
    int xStart = rightPanel.getLocation().getX();
    int xEnd = xStart + width;

    if (width > 0 || xEnd == windowWidth) {
        return true;
    } else if (xStart >= windowWidth || width <= 0) {
        return false;
    } else {
        fail("Right Panel is not shown correctly");
        return false;
    }
}

From source file:de.ppi.selenium.util.ScreenshotUtils.java

License:Apache License

/***
 * You can use this method to take your control pictures. Note that the file
 * should be a png./*from   ww w  . j  a v  a 2 s .c  o  m*/
 *
 * @param element the webelement
 * @param toSaveAs the file where the screenshot should be save.
 * @param wd the webdriver.
 * @throws IOException if something goes wrong writing the result.
 */
public static void takeScreenshotOfElement(WebElement element, File toSaveAs, WebDriver wd) throws IOException {

    for (int i = 0; i < MAXIMAL_NR_OF_RETRIES; i++) { // Loop up to 10x to
                                                      // ensure a clean
                                                      // screenshot was taken
        LOG.info("Taking screen shot of locator " + element + " ... attempt #" + (i + 1));

        // Scroll to element
        // TODO Improvement element.scrollTo();

        // Take picture of the page
        File screenshot;
        boolean isRemote = false;
        if (!(wd instanceof RemoteWebDriver)) {
            screenshot = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE);
        } else {
            Augmenter augmenter = new Augmenter();
            screenshot = ((TakesScreenshot) augmenter.augment(wd)).getScreenshotAs(OutputType.FILE);
            isRemote = true;
        }
        BufferedImage fullImage = ImageIO.read(screenshot);

        // Parse out the picture of the element
        Point point = element.getLocation();
        int eleWidth = element.getSize().getWidth();
        int eleHeight = element.getSize().getHeight();
        int x;
        int y;
        if (isRemote) {
            x = ((Locatable) element).getCoordinates().inViewPort().getX();
            y = ((Locatable) element).getCoordinates().inViewPort().getY();
        } else {
            x = point.getX();
            y = point.getY();
        }
        LOG.debug("Screenshot coordinates x: " + x + ", y: " + y);
        BufferedImage eleScreenshot = fullImage.getSubimage(x, y, eleWidth, eleHeight);
        ImageIO.write(eleScreenshot, "png", screenshot);

        // Ensure clean snapshot (sometimes WebDriver takes bad pictures and
        // they turn out all black)
        if (!isBlack(ImageIO.read(screenshot))) {
            FileUtils.copyFile(screenshot, toSaveAs);
            break;
        }
    }
}

From source file:dk.dma.ais.abnormal.web.StatisticDataIT.java

License:Open Source License

private static WebElement getMap() {
    // WebElement map = browser.findElement(By.cssSelector("svg#OpenLayers_Layer_Vector_27_svgRoot"));
    WebElement map = browser.findElement(By.cssSelector("div#map"));
    assertEquals(55, map.getLocation().getX());
    assertEquals(169, map.getLocation().getY());
    assertEquals(870, map.getSize().getWidth());
    assertEquals(524, map.getSize().getHeight());
    return map;//from  ww  w .j  a  v a2s.c  om
}

From source file:entities.GPTPlanet.java

@Override
public void openAd() {
    openAdsPage();// w  ww  .  ja va  2s.c  o m
    ArrayList<String> links = getAllAds();
    for (String link : links) {
        int timeout = 30;
        appendLog("-- Opening Ad: " + link);
        driver.get(homeUrl + link);
        while (timeout > 0) {
            List<WebElement> elements = null;
            try {
                elements = driver.findElements(
                        By.xpath("//div[@id='surfbar' and not(contains(@style,'display: none'))]"));
            } catch (UnhandledAlertException ex) {
                appendLog("\tError: UnhandledAlertException");
                elements = driver.findElements(
                        By.xpath("//div[@id='surfbar' and not(contains(@style,'display: none'))]"));
            }
            if (elements.size() > 0) {
                WebElement e = elements.get(0);
                if (e.getText().contains("Wait please") || (e
                        .findElements(By.xpath(
                                "./div/div[@id='progressbar' and not(contains(@style,'display: none'))]"))
                        .size() > 0)) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Neobux.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    timeout--;
                } else if (e.getText().contains("Thanks for watching!")
                        || e.getText().contains("Invalid Advertisement")
                        || e.getText().contains("already visited")) {
                    break;
                } else if (e
                        .findElements(
                                By.xpath("./div[@id='focusoff' and not(contains(@style,'display: none'))]"))
                        .size() > 0) {
                    appendLog("--- Off Focus...... ---");
                    driver.switchTo().window(getCurrentWindow());
                    e.findElement(By.xpath("./a")).click();
                } else {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Neobux.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    timeout--;
                    if (timeout < (timeout / 3)) {
                        driver.navigate().refresh();
                    }
                }
            } else if (driver
                    .findElements(By.xpath("//div[@id='vnumbers' and not(contains(@style,'display: none'))]"))
                    .size() > 0) {
                try {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Neobux.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    WebElement element = driver
                            .findElement(By.xpath("//*[@id=\"vnumbers\"]/table/tbody/tr/td[2]"));
                    Point point = element.getLocation();
                    File ss = (File) ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                    BufferedImage src = ImageIO.read(ss);
                    BufferedImage screen = src.getSubimage(point.getX(), point.getY(),
                            element.getSize().getWidth(), element.getSize().getHeight());
                    StaticImageScreenRegion region = new StaticImageScreenRegion(screen);
                    boolean found = false;
                    for (File file : new File("./src/imgs").listFiles()) {
                        if (file.isFile()) {
                            for (ScreenRegion match : region.findAll(new ImageTarget(ImageIO.read(file)))) {
                                found = true;

                                System.out.println("---location: " + point + " - " + element.getSize());
                                System.out.println("---match: " + match.getCenter());
                                System.out.println("-order: " + ((match.getCenter().getX() / 50) + 1));
                                System.out
                                        .println("- target: " + (point.getX() + 50 + match.getCenter().getX()));
                                new Actions(driver).moveToElement(element, 0, 0)
                                        .moveByOffset(match.getCenter().getX(), match.getCenter().getY())
                                        .click().perform();
                                break;
                            }
                        }
                        if (found) {
                            break;
                        }
                    }
                    if (!found) {
                        ImageIO.write(screen, "PNG", new File("./src/imgs/detected/notfound-"
                                + link.substring(link.lastIndexOf("=") + 1) + ".png"));
                    }
                    //                        break;
                } catch (Exception ex) {
                    Logger.getLogger(ScarletClicks.class.getName()).log(Level.SEVERE, null, ex);
                }

            } else {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Neobux.class.getName()).log(Level.SEVERE, null, ex);
                }
                timeout--;
                if (timeout < (timeout / 3)) {
                    driver.navigate().refresh();
                }
            }
        }
    }
}

From source file:influent.selenium.tests.TransactionsTableTest.java

License:MIT License

@Test
public void tableMultiResultsMultiPageTest() {

    ///////////////////////////////////////////////////////////////
    //Set Up: Select a card that has 100+ transactions where we can
    //highlight some of those rows.
    ///////////////////////////////////////////////////////////////
    getFlowViewResults("name:\"joe\" countryCode:\"PE\" datatype:loan matchtype:\"any\"", 1, false);

    List<WebElement> elements = driver.findElements(By.className("baseballcardContainer"));

    WebElement card1 = null;//from   w  w w .java 2  s.com
    for (WebElement webElement : elements) {
        if (webElement.isDisplayed()) {
            if (card1 == null) {
                card1 = webElement;
                break;
            }
        }
    }

    if (card1 == null) {
        throw new AssertionError("Couldn't find: baseballcardContainer element");
    }

    //Click card so add to file buttons appear
    card1.click();

    //Wait a few seconds for page to load. This is needed despite waiting for presence of element
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
    }

    WebElement element = (new WebDriverWait(driver, 120)).until(ExpectedConditions
            .presenceOfElementLocated(By.cssSelector("[title='branch right to outflowing destinations']")));

    element.click();

    //Wait a few seconds for page to load. This is needed despite waiting for presence of element
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
    }

    elements = driver.findElements(By.className("baseballcardContainer"));

    //WebElement card1 = null;
    WebElement lender = null;
    int x = 0;
    for (WebElement webElement : elements) {
        if (webElement.getLocation().getX() > x) {
            x = webElement.getLocation().getX();
            lender = webElement;
        }
    }

    lender.click();

    //Wait a few seconds for page to load. This is needed despite waiting for presence of element
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
    }

    ///////////////////////////////////////////////////////////////
    //We should now have a transactions table with 100 transactions
    ///////////////////////////////////////////////////////////////

    //Check results summary label
    element = (new WebDriverWait(driver, 120))
            .until(ExpectedConditions.presenceOfElementLocated(By.id("transactions-table-pagination-label")));
    assertEquals("Showing 1 - 100 of 111", element.getText());

    //check previous buttons disabled
    element = driver.findElement(By.id("transactions-previous-page"));
    assertEquals("btn btn-default disabled", element.getAttribute("class"));

    //check previous buttons enabled
    element = driver.findElement(By.id("transactions-next-page"));
    assertEquals("btn btn-default", element.getAttribute("class"));

    //check rows
    element = driver.findElement(By.id("transactions-table-body"));
    elements = element.findElements(By.tagName("tr"));
    assertEquals(100, elements.size());

    //test next button
    element = driver.findElement(By.id("transactions-next-page"));
    element.click();

    //Wait a few seconds for new table to load. We can't use ExpectedConditions.presenceOfElementLocated since they are already present
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
    }

    //Check results summary label
    element = (new WebDriverWait(driver, 120))
            .until(ExpectedConditions.presenceOfElementLocated(By.id("transactions-table-pagination-label")));
    assertEquals("Showing 101 - 111 of 111", element.getText());

    //check previous buttons enabled
    element = driver.findElement(By.id("transactions-previous-page"));
    assertEquals("btn btn-default", element.getAttribute("class"));

    //check previous buttons disabled
    element = driver.findElement(By.id("transactions-next-page"));
    assertEquals("btn btn-default disabled", element.getAttribute("class"));

    //check rows
    element = driver.findElement(By.id("transactions-table-body"));
    elements = element.findElements(By.tagName("tr"));
    assertEquals(11, elements.size());

    ///////////////////////////////////////////////////////////////
    //Test highlighting
    ///////////////////////////////////////////////////////////////

    //Setup
    //find card again
    element = driver.findElement(By.className("file"));
    card1 = element.findElement(By.className("baseballcardContainer"));

    //Click card again so branch right button appears
    card1.click();

    //Wait a few seconds for page to load. This is needed despite waiting for presence of element
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
    }

    element = card1.findElement(By.cssSelector("[title='highlight flow']"));
    element.click();

    //Wait a few seconds for page to load. This is needed despite waiting for presence of element
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
    }

    //Find lender again
    elements = driver.findElements(By.className("baseballcardContainer"));

    //WebElement card1 = null;
    lender = null;
    x = 0;
    for (WebElement webElement : elements) {
        if (webElement.getLocation().getX() > x) {
            x = webElement.getLocation().getX();
            lender = webElement;
        }
    }

    lender.click();
    //Wait a few seconds for new table to load. We can't use ExpectedConditions.presenceOfElementLocated since they are already present
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
    }

    //We should now have transactions from card2 highlighted in lender's transactions table

    //Check we have the correct number of highlighted rows
    element = driver.findElement(By.id("transactions-table-body"));
    elements = element.findElements(By.tagName("tr"));
    int highlightCount = 0;
    for (WebElement webElement : elements) {
        if (webElement.getAttribute("class") != null && webElement.getAttribute("class").length() >= 21
                && webElement.getAttribute("class").substring(0, 21).equals("transactionsHighlight")) {
            highlightCount++;
        }
    }

    assertEquals(5, highlightCount);

    //Check the first highlighted row is correct
    element = element.findElement(By.className("transactionsHighlight-0"));
    assertEquals("31 2012-11-30 status: paid; repayed: 181.65 (in PEN) $68.12 -", element.getText());

    //Test highlighting on next page
    element = driver.findElement(By.id("transactions-next-page"));
    element.click();

    //Wait a few seconds for new table to load. We can't use ExpectedConditions.presenceOfElementLocated since they are already present
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
    }

    //Check we have the correct number of highlighted rows
    element = driver.findElement(By.id("transactions-table-body"));
    elements = element.findElements(By.tagName("tr"));
    highlightCount = 0;
    for (WebElement webElement : elements) {
        if (webElement.getAttribute("class") != null && webElement.getAttribute("class").length() >= 21
                && webElement.getAttribute("class").substring(0, 21).equals("transactionsHighlight")) {
            highlightCount++;
        }
    }

    assertEquals(1, highlightCount);

    //Check the first highlighted row is correct
    element = element.findElement(By.className("transactionsHighlight-1"));
    assertEquals("104 2012-05-29 status: paid; loan: 1k (in PEN) - $375.00", element.getText());
}

From source file:io.appium.java_client.AppiumDriver.java

License:Apache License

/**
 * Convenience method for "zooming in" on an element on the screen.
 * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other.
 * NOTE://from   w w  w .  ja  v a 2  s  .com
 * This convenience method slides touches away from the element, if this would happen to place one of them
 * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api
 * instead of this method.
 *
 * @param el The element to pinch
 */
public void zoom(WebElement el) {
    MultiTouchAction multiTouch = new MultiTouchAction(this);

    Dimension dimensions = el.getSize();
    Point upperLeft = el.getLocation();
    Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2,
            upperLeft.getY() + dimensions.getHeight() / 2);
    int yOffset = center.getY() - upperLeft.getY();

    TouchAction action0 = new TouchAction(this).press(el).moveTo(el, center.getX(), center.getY() - yOffset)
            .release();
    TouchAction action1 = new TouchAction(this).press(el).moveTo(el, center.getX(), center.getY() + yOffset)
            .release();

    multiTouch.add(action0).add(action1);

    multiTouch.perform();
}

From source file:io.kahu.hawaii.cucumber.glue.html.HtmlSteps.java

License:Apache License

/**
 * Scroll to the element, this due to some dirty radiobutton tricks. And
 * force it a bit more to to center // And yes, do this for all elements. (
 * This is a known ChromeDriver V2.12 bug, if the element is not in the //
 * visible area then you 'can' have some troubles. ). Works for all elements
 * too ;-)/*  w  w  w. ja v  a  2  s  .co m*/
 *
 * @param element
 */
public void scrollToElement(WebElement element) {
    int y_coor = 0;

    try {
        y_coor = element.getLocation().y - 100;
        ((JavascriptExecutor) webDriver).executeScript("window.scrollTo(0," + y_coor + ")");
    } catch (Exception e) {
        throw new AssertionError("Could not scroll to element");
    }
}

From source file:io.selendroid.client.waiter.WaitingConditions.java

License:Apache License

public static Callable<Point> elementLocationToBe(final WebElement element, final Point expectedLocation) {
    return new Callable<Point>() {
        private Point currentLocation = new Point(0, 0);

        public Point call() throws Exception {
            currentLocation = element.getLocation();
            if (currentLocation.equals(expectedLocation)) {
                return expectedLocation;
            }//from www.j  a v a 2s.  co m

            return null;
        }

        @Override
        public String toString() {
            return "location to be: " + expectedLocation + " is: " + currentLocation;
        }
    };
}

From source file:io.selendroid.nativetests.NativeElementInteractionTest.java

License:Apache License

/**
 * Based on the default test emulator used to verify build that has a resolution of 320x480
 * pixels./*w w w  .  j  a  v a  2  s  .  c o  m*/
 */
@Test
public void shouldGetLocationOfElement() {
    openStartActivity();
    WebElement button = driver().findElement(By.id("waitingButtonTest"));
    Point location = button.getLocation();
    Assert.assertEquals(location.x, 0);
    // this is not perfect but guarantees that it works on different screen sizes
    Assert.assertTrue(location.y >= 247);
}

From source file:io.selendroid.webviewdrivertests.touch.TouchFlickTest.java

License:Apache License

@Test
public void testCanFlickVerticallyFromWebElement() {
    openWebdriverTestPage(HtmlTestData.LONG_CONTENT_PAGE);

    WebElement link = driver().findElement(By.id("link3"));
    int y = link.getLocation().y;
    // The element is located at the bottom of the page,
    // so it is not initially visible on the screen.
    assertTrue(y > 4200);/* ww w  . j  av  a 2  s. c o  m*/

    WebElement toFlick = driver().findElement(By.id("imagestart"));
    Action flick = getBuilder(driver()).flick(toFlick, 0, -600, FlickAction.SPEED_NORMAL).build();
    flick.perform();
    y = link.getLocation().y;
    // After flicking, the element should now be visible on the screen.
    assertTrue("Expected y < 4000, but got: " + y, y < 4000);
}