0 votes
1 view
in Devops and Agile by (19.8k points)

I am having an issue with Selenium WebDriver. I try to click on a link that is outside the window page (you'd need to scroll up to see it). My current code is fairly standard:

menuItem = driver.findElement(By.id("MTP"));

menuItem.click();

// I also tried menuItem.sendKeys(Keys.RETURN);

I know I could scroll up, and it would work in this case. But in a case where you have a long list of items, you don't necessarily know how far you have to scroll down.

Is there any way to click on a link that is not on the visible part of the page (but that would be visible if you scroll)?

As a side note, I'm using Firefox, but I am planning to use IE7/8/9 and Chrome as well.

Any help would be greatly appreciated.

Edit: I'm afraid I can't give the source code, as the company I work for doesn't allow it, but I can give the code of the link I want to click on:

<div class="submenu">

  <div id="MTP">Link title</div>

</div>

The exact same code works when the link is visible, is only when it does not work.

Edit2: Actually, oddly enough, it doesn't raise an exception and just goes to the next instruction. So basically, what happens is:

menuItem = driver.findElement(By.id("MTP")); // no exception

menuItem.click();  // no exception

//... some code ensuring we got to the next page: timeout reached

driver.findElement(By.id("smLH")).click(); // NoSuchElementException, as we're on the wrong page

1 Answer

0 votes
by (63.4k points)

It may be occurring as a result of your header component or the footer component might be blocking the view of the component you wish to perform an action on. Selenium tries to scroll to the element position when it's to perform some action on the element (I am using element WebDriver v3.4.0).

Here is a solution-

private WebElement scrollToElementByOffset(WebElement element, int offset) {

    JavascriptExecutor jse = (JavascriptExecutor) driver;

    jse.executeScript("window.scrollTo(" + element.getLocation().getX() + "," + (element.getLocation().getY()

            + offset) + ");");

    return element;

}

The above function scrolls the view to the element, then scrolls more by the offset you give.

And you can call this method by doing something like -

WebElement webElement = driver.findElement(By.id("element1"));

scrollToElementByOffset(webElement, -200).click();

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...