locate an element in current view

When I use the method WebElement#findElement(By) with By.cssSelector, it searches for the element through the whole page. But I want to restrict the selection by current-view-only. I don't want to allow Selenium to "use scrollbar". How can I achieve this?

Answers


The way to go for this could be in the way of getting all the elements on the page and then filtering out those out of viewport.

WebElement.getLocation() is a ground tool for this.

If you're in the left-top corner of the page (default after the load), you can use window.innerHeight and window.innerWidth (most browsers, but IE9+).

// assuming JS is enabled for this instance of driver
JavascriptExecutor js = (JavascriptExecutor)driver;

int viewportWidth = (Integer)js.executeScript("return window.innerWidth;");
int viewportHeight = (Integer)js.executeScript("return window.innerHeight;");

List<WebElement> list = driver.findElements(By.cssSelector("whatever"));
for (Iterator<WebElement> iter = list.iterator(); iter.hasNext(); ) {
    WebElement elem = iter.next();
    Point p = elem.getLocation();
    if ((p.getX() > viewportWidth) || (p.getY() > viewportHeight)) {
        iter.remove();
    }
}

If you cannot say for sure that the viewport will be in its default position (at coordinates [0, 0]), you can add window.mozInnerScreenX and window.mozInnerScreenY (Firefox 3.6+ required) to the condition. Or, possibly better, window.scrollX and window.scrollY.

You also have to define whether to include partially shown elements or not and adjust the algorithm accordingly (WebElement.getSize() to the rescue!).

If you'll have trouble that after the search, the viewport changed, try to scrool back to the original position via window.scroll().


Need Your Help

open source business intelligence solutions

open-source data-warehouse business-intelligence

which open source business intelligence solution would you recommend?