javaseleniumautomationui-automation

Can't get to element in Selenium (Zoom and Scroll not working)


The website that I am running selenium on has some components that fall off the screen. I have tried to scroll down to it, zoom out of the page to make it fit and so on. It is a div modal that contains a button that I need to press.

Here are my previous attempts:

1) Scrolling to the location The first issue was that whenever I try scrolling, using code or using my own mouse in the window, all that would happen was that the page behind the modal would scroll rather than the modal itself scrolling. This only happens when running Selenium. As such, the below code did not work.

JavascriptExecutor js = ((JavascriptExecutor)driver);
js.executeScript("window.scrollTo(0," + driver.findElement(By.xpath("//*[@id=\"manual-order-modal-ignore-validation\"]")).getLocation().x + ")");

It actually scrolls but like I said above, the necessary element never ended up on the screen.

2) Zooming out #1

I tried using Javascript to zoom out of the page which did the job but it apparently threw off my Selenium driver, as it was trying to click on the original location of the button and was not able to find it there.

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.body.style.zoom='80%'");

Likewise, I also tried using the below solution but it didn't work either.

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.body.style.transform='scale(0.8)'");

3) Zooming out #2

I tried sending multiple key strokes but the only thing I got was an error saying "cannot focus element"

WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.COMMAND, Keys.SUBTRACT));

4) Zooming out #3

I tried using the robot class but it didn't scroll at all, it just sat there.

for (int i=0; i< 6; i++)
{
   Robot robot = new Robot();
   robot.keyPress(KeyEvent.VK_CONTROL);
   robot.keyPress(KeyEvent.VK_MINUS);
   robot.keyRelease(KeyEvent.VK_CONTROL);
   robot.keyRelease(KeyEvent.VK_MINUS);
   System.out.println("zoom out")
}

The "zoom out" gets printed but no actions are taken.

As you can see, I have looked up and tried many solutions to no avail. If you have any ideas on how to solve this issue, it would be much appreciated! Thank you in advance.


Solution

  • So even though I could never scroll down to the button, turns out you can just click it by executing Javascript in selenium. It's kinda hacky but here's my approach was this:

    ((JavascriptExecutor)driver); js.executeScript("document.getElementById(\"manual-order-sav‌​e-button\").click()"‌​);

    Doing so allowed me to click on it without it being visible.

    Disclaimer: I realize that this is not in the spirit of UI-automation because it doesn't quite simulate a user's actions, but if you are stuck in a situation like me where WebDriver acts incorrectly, this hack might work.

    Thank you kushal for the input.