Selenium webdriver can't click on a link outside the page

Viewed 41091

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, only when it is not does it not work.

Edit2: Actually, oddly enough, it doesn't raise any 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.
11 Answers

Instead of move the scrollbar to the button position, which sometimes it didn't work for me, I send the enter key to the button

var element = driver.FindElement(By.Id("button"));
element.SendKeys(Keys.Enter);

This works for me (in c#)-

item = driver.findelement(by.....);
item.SendKeys(Keys.LeftControl);
item.Click();

I have used below method to solve the problem of element not present in the visible area. The code scrolls down the webpage, till selenium operations can be performed on the element. Change the co ordinate of Y-axis and value of i as per requirement.

public void scrooling(By ele) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            try {
                driver.findElement(ele);
                break;
            } catch (ElementNotVisibleException e) {
                JavascriptExecutor js = (JavascriptExecutor) driver;
                js.executeScript("window.scrollBy(0,400)");
                System.out.println("inside ElementNotVisibleException block");
                Thread.sleep(3000);
            } catch (NoSuchElementException e) {
                JavascriptExecutor js = (JavascriptExecutor) driver;
                js.executeScript("window.scrollBy(0,400)");
                System.out.println("inside NoSuchElementException block");
                Thread.sleep(3000);
            }

        }


    } 
Related