Scrolling using Selenium WebDriver with Java - java

I am using Selenium WebDriver to automate my browser tests. My browser header is floating and is always present irrespective of the browser scroll.
So when I click on certain elements that are present below the current visible region of the browser, selenium tries to scroll the element into view and click them.
But because of the auto scrolling as such the elements are scrolled behind the floating header and when any action is performed on them, the elements in the page header get clicked.
is there any way to limit the default scroll of the WebDriver?

Locatable hoverItem = (Locatable) driver.findElement(By.xpath("//li[text()='Reklama w Google']"));
int y = hoverItem.getCoordinates().getLocationOnScreen().getY();
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,"+y+");");

If you want to scroll on the firefox window using selenium webdriver, one of the way is to use javaScript in the java code, The javeScript code to scroll down is as follows:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight," +
"document.body.scrollHeight,document.documentElement.clientHeight));");

You can scroll to the necessary location using javascript You need to use the scrollTo method rather than the scrollBy method for it to work.
public void scrollToElement(By by) {
Locatable element = (Locatable) selenium.findElement(by);
Point p= element.getCoordinates().getLocationOnScreen();
JavascriptExecutor js = (JavascriptExecutor) selenium;
js.executeScript("window.scrollTo(" + p.getX() + "," + (p.getY()+150) + ");");
}

Scroll to top can be done:
private void scrollToTop() {
JavascriptExecutor js = (JavascriptExecutor) webDriver;
js.executeScript("window.scrollTo(0, 0);");
}

Simple use the
.sendKeys(Keys.PAGE_DOWN);
when your element was visible, just click on it, by .click(element).perform();
for me work something like this:
clicker = new Actions(driver);
clicker.sendKeys(Keys.PAGE_DOWN);
Thread.sleep(1000);
clicker.click(button).perform();
Thread.sleep(1000);

For scrolling down:
System.setProperty("webdriver.chrome.driver",
"/home/shreetesh/chromedriver");
WebDriver driver = new ChromeDriver();
String url = "https://en.wikipedia.org/wiki/Main_Page";
driver.get(url);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("scroll(0, 25000);");
To scrolling up just replace the value of scroll with (2500, 0).

Use below code for scrolling up and scrolling down
Actions dragger = new Actions(driver);
WebElement draggablePartOfScrollbar = driver.findElement(By.xpath("<Scroll bar Element >"));
// drag downwards
int numberOfPixelsToDragTheScrollbarDown = 50;
for (int i=10 ; i<500 ; i=i+numberOfPixelsToDragTheScrollbarDown) {
try {
// this causes a gradual drag of the scroll bar, 10 units at a time
dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0,numberOfPixelsToDragTheScrollbarDown).release().perform();
Thread.sleep(1000L);
} catch(Exception e1){}
}
// now drag opposite way (downwards)
numberOfPixelsToDragTheScrollbarDown = -50;
for (int i=500;i>10;i=i+numberOfPixelsToDragTheScrollbarDown){
// this causes a gradual drag of the scroll bar, -10 units at a time
dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0,numberOfPixelsToDragTheScrollbarDown).release().perform();
Thread.sleep(1000L);
}

I recently had this problem due to a Drupal menu blocking the element when I ran this code:
public void scrollTo(WebElement x) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", x);
}
After referencing this page, I updated to set the boolean to false using this code, and it works great:
public void scrollTo(WebElement x) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(false);", x);
}

Related

How to make a click of a few seconds

First post ...
I discovered javascript and selenium, I'm trying to make a left click of a duration of 1 or 2 seconds.
It is easy to make a right click or a double click, but how to make a long click?
Thank you for your support.
Double click is ok :
Actions action = new Actions(driver);
WebElement link = driver.findElement(By.ID ("Element ID"));
action. doubleClick (link).perform();
Click with executeScript ok:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.querySelector(script).click();",Arguments);
At this point I have no track for the long click ...
You can try this below option
public void loingClick(WebDriver driver,WebElement element, int numberOfSeconds) throws Exception
{
Actions action = new Actions(driver);
action.clickAndHold(element).build().perform();
Thread.sleep(1000*numberOfSeconds);
action.moveToElement(element).release();
}

How to scroll horizontally extreme left when scroll bar is in middle of the page using selenium java

On page, the horizontal scroll bar is in middle and I need to scroll it to extreme left to see the first column
I have tried for different ways as seen below:
WebElement userPhase = driver.findElement(By.xpath("//div[#class='ag-header-row']//div[#col-id='user_Phasing_Attribute_1']"));
actions.moveToElement(userPhase).build().perform();
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement Element = driver.findElement(By.linkText("VBScript")); // This will scroll the page Horizontally till the element is found
js.executeScript("arguments[0].scrollIntoView();", Element);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("<document.getElementByxpath('//div[#col-id='user_Phasing_Attribute_1']').scrollLeft += 250>", "");
((JavascriptExecutor)driver).executeScript("window.scrollBy(-2000,0)");

Selenium WebDriver is not clicking on first button

I have a List containing 5 'Buy' buttons. Selenium WebDriver is not clicking the first 'Buy' button but clicks the remaining 4 just fine. Ran a println and it shows all 5 buy buttons being found by WebDriver.
I have tried switching the order of buttons in the List, I have attempted to debug it, I have included explicit wait also but nothing is helping. Anyone has any clues?
My code is as follows:
for (int i = 0; i < allProductsOnsite.size(); i ++) {
//System.out.println(allProductsOnsite.get(i).getText());
if (prodsToBuy.contains(allProductsOnsite.get(i).getText())) {
System.out.println("Found -------" + allProductsOnsite.get(i).getText() );
WebDriverWait wt = new WebDriverWait(driver, 15);
wt.until(ExpectedConditions.visibilityOfAllElements(allProductsOnsite));
allBuyButtons.get(i).click();
}
}
Try to click using JavascriptExecutor
WebElement element= driver.findElement(By.xpath(".//*[#id='loginButton']/div"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
Also use some wait if needed before this code
Hope this will help you :)

selenium firefox modal displays as a pop-up window, not a modal

I'm trying to use Selenium to test out a form on a website that consists of multiple pages. There are modals that are suppose to appear on some of the pages based on options that are selected. Currently I'm having trouble getting Selenium to work properly with Fireforx and the modals. Chrome acts as expected, and I haven't bothered with I.E. yet.
When I work through the pages manually with Firefox, everything works as expected.
When I run my Selenium script the modal displays like a Windows pop-up window, not a modal.
I'm using driver.switchTo().alert().accept(); to handle the modals, and the first modal I encounter will close, but once I get to the next page the Selenium code is unable to find any of the elements on the page.
Here is the code I use to click a button:
public void pushButton(String[] values) {
System.out.println("\t Click (" + values[1] + ")");
setLocator(values[0], values[1]);
try {
clickWhenReady(locator).click();
} catch (Exception e) {
System.out.println("Could not find id or xpath value: " + values[1]);
e.printStackTrace();
}
}
private void setLocator(String byType, String value) {
if(byType.toUpperCase().equals("ID")) {
locator= By.id(value);
} else if(byType.toUpperCase().equals("XPATH")){
locator= By.xpath(value);
}
}
private WebElement whenReady(By locator){
WebElement element = (new WebDriverWait(driver, 30))
.until(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
private WebElement clickWhenReady(By locator){
WebElement element = (new WebDriverWait(driver, 30))
.until(ExpectedConditions.elementToBeClickable(locator));
return element;
}
First of all, modals are not alerts so, driver.switchTo().alert().accept(); will probably not going to buy you anything.
The real issue could be the modals take longer to fade out and blocking Selenium to interact with the page. Your best bet will be to try waiting for the modal to completely disappear from the dom and then try interacting with the elements. For that you can use invisibilityOfElementLocated of ExpectedConditions or similar mechanism. See this

Unable to click a mouse hover link using Selenium WebDriver with Java

I am trying to click a mouse hover link using the code below. The webdriver (v.2.35) doesn't throw any error but the element isn't clicked. Can somebody help me figure out what's wrong?
String URL = "http://www.kgisliim.ac.in/"
String menu ="Alumni>Register"
driver.get(URL);
String[] menuItems = menu.split(">");
Actions actions = new Actions(driver);
WebElement tempElem;
for (int i =0 ; i< menuItems.length ; i++) {
tempElem = driver.findElement(By.linkText(menuItems[i].trim()));
actions.moveToElement(tempElem).build().perform();
}
actions.click();
actions.perform();
NOTE: The above code works fine in the below scenario
String URL = "http://www.flipkart.com/"
String menu ="Clothing>Jeans"
You can try this:
WebDriver driver=new FirefoxDriver();
driver.get("http://www.kgisliim.ac.in/");
Actions actions=new Actions(driver);
WebElement menuHoverLink=driver.findElement(By.linkText("Alumni"));
actions.moveToElement(menuHoverLink);
//driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
WebElement subLink=driver.findElement(By.cssSelector(".options>ul>li>a"));
actions.moveToElement(subLink);
actions.click();
actions.perform();
Since the menu on http://www.kgisliim.ac.in/ takes a second to slide out, you could add a WebDriverWait to make sure the submenu has time to become visible before moving the cursor to it. Try replacing the first line in your for loop with the following line. This will wait a maximum of 5 seconds for the submenu (but will return the WebElement as fast as possible within that time).
tempElem = new WebDriverWait(driver, 5).until(ExpectedConditions
.elementToBeClickable(By.linkText(menuItems[i].trim())));
I stumbled across a similar issue recently, with phantomJS and ghostdriver. In my case, the problem was the window size - the HTML element was outside the visible area and my mouse movements were having no effect (default size is 400x300, which is rather small).
You can check the window size with
driver.manage().window().getSize()
And you can change it with
driver.manage().window().setSize(new Dimension(width, height));

Categories