Selenium - complete ajax loading autoscroll to bottom of page - java

I have a webpage where when you scroll to the bottom it then loads more results via ajax. You can do several iterations of this before it completes. Bit like what facebook does.
I am trying to write a selenium script to keep going to the end of the page until it completes.
Something like this sort of half completes it.. I just don't know how to determine if page is at the bottom - so i can put it inside a loop of some sort?
My Attempt
By selBy = By.tagName("body");
driver.findElement(selBy).sendKeys(Keys.PAGE_DOWN);
System.out.println("Sleeping... wleepy");
Thread.sleep(5000);
driver.findElement(selBy).sendKeys(Keys.PAGE_DOWN);
System.out.println("Sleeping... wleepy1");
Thread.sleep(3000);
//etc...
Could Look like this?
hasScroll() isnt a real method. I put that there to demonstrate what im trying to achieve
while (driver.findElement(By.tagName("body")).hasScroll()) {
driver.findElement(selBy).sendKeys(Keys.PAGE_DOWN);
System.out.println("Sleeping... wleepy");
Thread.sleep(2000);
}

Try this approach:
//Get total height
By selBy = By.tagName("body");
int initialHeight = driver.findElement(selBy).getSize().getHeight();
int currentHeight = 0;
while(initialHeight != currentHeight){
initialHeight = driver.findElement(selBy).getSize().getHeight();
//Scroll to bottom
((JavascriptExecutor) driver).executeScript("scroll(0," + initialHeight + ");");
System.out.println("Sleeping... wleepy");
Thread.sleep(2000);
currentHeight = driver.findElement(selBy).getSize().getHeight();
}
Hope help!

Related

Java Selenium - navigating with the website's page-navigator gets stuck

I am trying to move through website pages using the website's page navigator, but it always stops clicking at page 13.
This is the page navigator:
This is my code:
for (int i = 1; i <= numOfPages; i++) {
customWebDriver.getWebDriver().findElement(By.className("css-3a6490")).click();
Thread.sleep(3000);
}
This is the HTML structure:
I have also tried using the element under css-3a6490, css-15a7b5o:
for (int i = 1; i <= numOfPages; i++) {
customWebDriver.getWebDriver().findElement(By.className("css-15a7b5o")).click();
Thread.sleep(3000);
}
but it also didn't work.
Does someone knows what is the problem?
Thanks
Try with:
customWebDriver.getWebDriver().findElement(By.xpath("//button[#class='css-19a323y']//following-sibling::button[1]")).click();
Explanation of Xpath: A button with class css-19a323y (Which is the current selected page) and then selecting the following button (Which is the next available page)
Also use more time for Thread.sleep(3000); because sometimes when you make pagination it takes more time, so better add more time, or using WebdriverWait and Expected conditions, here an example:
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

how to scroll the horizontal bar in a grid using selenium

How to scroll the horizontal bar in a grid using selenium. This should be repeated in multiple selections. I have to select the value and click submit. I have to check all the column headers. But, there are 46 columns. Please help. I am unable to move it.
List<WebElement> gridlabellist = driver.findElements(By.xpath(".//*[#id='gview_list']/div[3]/div/table/thead/tr/th"));
List<String> all_gridlabellist=new ArrayList<>();
Thread.sleep(1000);
int gl;
System.out.println(gridlabellist.size());
for(gl=0; gl<gridlabellist.size(); gl++)
{
String gridlabelname=gridlabellist.get(gl).getText();
boolean dislabel=gridlabellist.get(gl).isEnabled();
//System.out.println(labelname);
if((gridlabelname != null) && (gridlabelname.length()!=0) && dislabel)
{
System.out.println("\nGrid Label Names displayed: " + gridlabelname);
((JavascriptExecutor)driver).executeScript("window.scrollBy(2000,0)");
System.out.println("\nGrid Label Names displayed: " +gridlabelname);
}
all_gridlabellist.add(gridlabellist.get(gl).getText());
}
its a very old question but still relevant enough to answer with alternative ways, another way to solve this problem is to zoom, zoom to 50-30% or even 10%; this will load all the columns and then read them using xpath.
Try a different approach & test if it works for you
WebElement scroll = driver.findElement(By.xpath("//blah-blah"));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(
driver.execute_script("arguments[0].scrollIntoView()", scroll);

Scrolling to a WebElement and clicking on it

I am new to automation and am practicing on the flipkart website.
On the page:
http://www.flipkart.com/mobiles/pr?sid=tyy,4io&otracker=clp_mobiles_CategoryLinksModule_0-2_catergorylinks_11_ViewAll
... when I try to click an element that is not in view of the page by scrolling to it, I get the exception: Element is not clickable
Below is the code:
WebElement mobile = driver.findElement(By.xpath ("//a[#title='Apple iPhone 6S (Silver, 128 GB) ']"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].scrollIntoView();", mobile);
mobile.click();
I believe this issue is occurring because of the header available in flipkart: even though the window is getting scrolled to that particular element, the header is covering the element so it's not possible to click on it.
Can anyone help resolve this?
you can try like this
Case where you want to click on a element that is not in view of the page (without scrolling) try below
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(
"http://www.flipkart.com/mobiles/pr?sid=tyy,4io&otracker=clp_mobiles_CategoryLinksModule_0-2_catergorylinks_11_ViewAll");
driver.manage().window().maximize();
// Take everything on the page in list first .
List<WebElement> completecalContent = driver.findElements(By.xpath("//*[#class='fk-display-block']"));
System.out.println(completecalContent.size());
// printing all elements
for (int i = 0; i < completecalContent.size(); i++) {
System.out.println("Print complete Content : " + completecalContent.get(i).getText());
if (completecalContent.get(i).getText().equals("Apple iPhone 5S (Space Grey, 16 GB)")) {
// move to a specific element
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();",
completecalContent.get(completecalContent.size() - 1));
// move slightly up as blue header comes in the picture
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,-100)");
// then click on the element
completecalContent.get(i).click();
}
}
}
Case where you want to scroll then in that case update above code with these lines.
A. if you want to scroll to the bottom of the page then
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)");
B. if u want to scroll to a specific element then try this
WebElement element = driver.findElement(By.xpath("xpath to element"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView();", element);
C. if you want to scroll on the basis of coordinates then try this
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");
Instead of scrolling up to web element you can try scrolling to little bit down in page like
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(250, 0)"); //x value '250' can be altered
Else you can try scrolling to element which is good enough above to required element. It means in code you tried instead of taking required webelement just scroll upto web element above the required so that the header does not cover required element.
Thank You,
Murali
Hey if you are not certain about the element's position on the page, you can find the co-ordinates at run time and then execute your text.
You can get elements co-ordinate by using Point
Point point = element.getLocation();
int xcord = point.getX();
int ycord = point.getY();
You can also get the dimensions of a webelement like its Height and Width using Dimension
Once you have the x and y co-ordinates and you have its dimensions. You can write your code to scroll till that particular co-ordinates on the page.
Hope it helps!

Scrolling an ajax page completely using selenium webdriver

I am trying to scroll a page completely using this code:
JavascriptExecutor js = (JavascriptExecutor) Browser;
js.executeScript("javascript:window.onload=toBottom();"+
"function toBottom(){" +"window.scrollTo(0,Math.max(document.documentElement.scrollHeight," +"document.body.scrollHeight,document.documentElement.clientHeight));" +"}");
js.executeScript("window.status = 'fail';");
//Attach the Ajax call back method
js.executeScript( "$(document).ajaxComplete(function() {" + "status = 'success';});");
js.executeScript("window.status = 'fail';");
//Attach the Ajax call back method
js.executeScript( "$(document).ajaxComplete(function() {" +"status = 'success';});");
This code works fine and scroll the page for the first attempt but when page is scrolled down, new data appears at the page and this code failed to scroll it again.
So what I need is that someone will help me to scroll the page till end until scrolling is completed.
Do I use any loop for this?
Help/Suggestions/Response will be appreciated!
I had a page with similar functionality and another question I answered previously. I am not familiar with any generic way to know if page does not have any other elements on load. In my case the page is designed to load 40/80(forgot the exact count) element in each scroll. Since, most of the cases I know an estimated number of scroll(since I am using a test company and I know how many element present for that in db) I can estimate the number of scroll and did the following to handle that page.
public void ScrollPage(int counter)
{
const string script =
#"window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));";
int count = 0;
while (count != counter)
{
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
js.ExecuteScript(script);
Thread.Sleep(500);
count++;
}
}
See my other answer here
Java equivalency code
public void ScrollPage(int counter) throws InterruptedException {
String script = "window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));";
int count = 0;
while (count != counter)
{
((JavascriptExecutor)driver).executeScript(script);
Thread.sleep(500);
count++;
}
}
Use
ScrollPage(10);
in wherever the scroll is necessary
So, I would do something like that:
bool pageEnded = false;
while (!pageEnded) {
JavascriptExecutor js = (JavascriptExecutor) Browser;
js.executeScript("window.scrollTo(0, document.body.offsetHeight);");
pageEnded = (String)js.executeScript("return document.readyState;") ? true;
}
The best Way to do this is the following (implemented in Python):
import time
def loadFullPage(Timeout):
reachedbottom = None
while not reachedbottom:
#scroll one pane down
driver.execute_script("window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));");
time.sleep(Timeout)
#check if the bottom is reached
a = driver.execute_script("return document.documentElement.scrollTop;")
b = driver.execute_script("return document.documentElement.scrollHeight - document.documentElement.clientHeight;")
relativeHeight = a / b
if(relativeHeight==1):
reachedbottom = True
You have to find a efficient Timeout for your internet connection. A timeout of 3 seconds worked well for me.

Move slider in Selenium Webdriver with Java and Firefox

I have a problem using Selenium Webdriver (version 2.32.0) and Firefox (21.0), trying to change the values on a slider.
I wrote a Java code like this:
private void selectGiftCardPrice() throws TestingException {
try {
WebElement slider = getDriver().findElement(
By.cssSelector("div.sliderHandle"));
Actions move = new Actions(getDriver());
move.dragAndDropBy(slider, 90, 0);
move.build().perform();
sleep(4000);
} catch (Exception e) {
log.info(e);
throw new TestingException("e");
}
I tried out every code I found on the Web, every change, and it still does not work. It does not show any problem, just finds the element, and does nothing. Any idea what it is, or what can I do?
EDIT from comment:
I finally made it working with jQuery slider demo
driver.get("http://jqueryui.com/resources/demos/slider/multiple-vertical.html");
WebElement slider = driver.findElement(By.xpath("//div[1]/a[contains(#class,'ui-slider-handle')]"));‌
But it is still not working for me with jQuery UI Slider demo page using Xpath //div[#id='slider']/a. What is the problem?
This code works absolutely fine for me.
program handles slider of website : Homeshope18.com
Check it out:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.homeshop18.com/fashion-jewellery/category:15143/filter_Theme:%28%22Traditional+Wear%22+%22Cuff+%26+Kada%22+%22Daily+Wear%22+%22Maang+Tikka%22+%22Openable+Round%22+%22Round%22+%22Openable+Oval%22%29/sort:Popularity/inStock:true/?it_category=HP&it_action=JW-HPSP01&it_label=HP-HPSP01-131021235900-PD-JW-ZC-VK-SC_DiwaliFestWeddingJewellery&it_value=0");
WebElement slider = driver.findElement(By.xpath("//*[#id='slider-range']/a[1]"));
Thread.sleep(3000);
Actions moveSlider = new Actions(driver);
Action action = moveSlider.dragAndDropBy(slider, 30, 0).build();
action.perform();
Using Actions class, firs use clickAndHold("WebElemnt");
Then to move horizontally we need to move in the Y direction of the screen so we can use movebyoffset, i.e X-axis: 0 & Y axis: 40px
To move vertically we need to move in the X direction of the screen so we can use movebyoffset, i.e X-axis: 40px & Y axis: 0
The sample code would be :
Actions slider=new Actions(driver);
slider.clickAndHold("WebElemnt");
slider.movebyoffset(0,40).build.perform();

Categories

Resources