Scroll aside div with Selenium - java

I'm working on a program that uses Selenium and I'm trying to scroll on some aside div of the document.
I firstly tried the following line of code but this only scrolls the main part of the HTML document:
((JavascriptExecutor) driver).executeScript("scrollBy(0, 500)");
So I tried to execute this:
((JavascriptExecutor) driver)
.executeScript("document.getElementsByClassName('aside-div')[0].scroll(0,100)");
This compile and executes without any error but the section I want to scroll through doesn't scrolls. How can I do this?

The best practice is to always use the javascript code on your browser console before actual implementation.
Also, plz make sure scroll(x,y), the value should be according to the scroll it can be either (1000,0) or (0,1000) negative-positive according to the requirement. Kindly choose accordingly.
Ok so coming back to your actual problem, what I feel is you are incorrectly using the code
Either you have been using scroll(0,1000) instead of scroll(1000,0) so on..
You have not mentioned the exact element locator.
PS: Please provide the HTML for in-depth debugging.
Meanwhile, you can checkout the below code:
((JavascriptExecutor) driver).executeScript("document.getElementsByClassName('aside-div'[0].scroll(0,1000)");
//OR
((JavascriptExecutor) driver).executeScript("document.getElementsByClassName('aside-div'[0].scroll(1000,0)");
//OR
WebElement elementToScroll = driver.findElement(By.cssSelector(".aside-div"));
((JavascriptExecutor) driver).executeScript("arguments[0].scroll(1000,0);", elementToScroll);
Please provide the exact element locator to use below code:
Example:
WebElement elementToScroll = driver.findElement(By.cssSelector(".aside-div table tr td"));
//This will scroll the page Horizontally till the element is found
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", elementToScroll);

Related

JAVA - Hidden Class Selenium

I am a beginner in selenium and I would like to press a file submission field.
I have already done a whole code to connect to the page, click on the buttons etc. (everything works, my driver is good)
But impossible to click on adding file
I looked on the internet how to do it, I added time, tried to browse the frames, used javascript for the hidden class... I tried all the buttons in the field and it doesn't detect them.
Add File
Source code
Thread.sleep(2000);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,1000)");
WebDriverWait wait = new WebDriverWait(driver, 60);// 1 minute
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*#id=\"yui_3_17_2_1_1584634673387_348\"]/div[1]/div[1]/a")));`
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id="yui_3_17_2_1_1584634673387_348"]/div[1]/div[1]/a"}
Do you have an idea ?
The primary issue I observed looking at the code is the incorrect locator in your Explicit Condition element checking line. It can be replaced with below code:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='yui_3_17_2_1_1584634673387_348']/div[1]/div[1]/a")));
Basic XPath Syntax for reference though it has it's variations:
//tagname[#attrbute='value']
Additional advice Though I am not sure about the application you are automating, but the ID is likely to be changed. Based on the DOM Structure you have provided in the link above I would say change the locator to something on the lines of:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#role='button'][#title='Add..']")));

Why am I not able to click the web element using the following code, even though I can see that the controller is tracking the xpath?

click here to check the page I am working on
The following is the java code:
driver.findElement(By.xpath(".//*[#id='ref_2665398031']/li[4]/a/span1")).click();
The element is actually in the left navigation pane.
Here when this particular statement is getting executed, I can see that browser is moving down, but it does not click that element.
You have not properly written the xpath:
".//*[#id='ref_2665398031']/li[4]/a/span1"
it should be : "//[#id='ref_2665398031']/li[4]/a/span[1]"
and if using WebDriver then
"//[#id=\"ref_2665398031\"]/li[4]/a/span[1]"
After correcting above if still error exists:
You are using a relative path which is relative to the element having id='ref_2665398031.
This id seems to be generated dynamically.
Please confirm two things:
Your code is not giving element not found error.
Page refresh is not changing this id. (If it is being generated dynamically than it will change on page refresh.)
Otherwise try using different approach:
driver.findElement(By.xpath("//*[contains(text(), '50% Off or more')]"));
Use this xpath:
driver.findElement(By.xpath("//ul[#id='ref_2665398031']/li[4]/a/span[1]")).click();
Try Below xpath it is working for me
driver.findElement(By.xpath("//ul[contains(#id,'ref_2665398031')]/li[4]/a")).click();
Try JavaScriptExecutor instead of using normal Selenium click method.
WebElement element = driver.findElement(By.xpath(".//span[contains(text(),'50% Off or more')]"));
((JavascriptExecutor) driver).executeScript("return arguments[0].click();", element);

selenium.ElementNotVisibleException: Element is not currently visible JAVA

I am working on selenium, while running Java code I tried to CLICK a menu from the web page but encounter error of selenium.ElementNotVisibleException: Element is not currently visible Kindly advise on this matters . Thanks you
HTML code for text field :
<li onclick="goin('pages/AbcProxy/proxyGroupList.do')>
TESTABC
JAVA code:
WebdriverWait wait = new WebDriverWait(driver,50);
wait until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/div/ul/li[12]/a")));
presenceOfElementLocated checks if the element exists in the DOM. To check if the element is visible use visibilityOfElementLocated
WebdriverWait wait = new WebDriverWait(driver,50);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/ul/li[12]/a")));
element.click();
It might be that your xpath is to a different a element that is invisible (css display none or such).
It would be better to use some id first (maybe for the parent ul?) and then a relative xpath from there, full xpaths from root are not recommended as it makes the test very brittle

How to scroll a specific DIV using Selenium WebDriver with Java?

Some of WebElements are not recognized by WebDriver, WebDriver fails to find the element which is not visible in browser's visible area.
In order to make the WebElement viewable by WebDriver, We need to make that element to visible in browser's view to do scroll down on particular div!
How can I perform my action(scroll down and click) on particular area of my webpage. I tried lot, doesn't helped me.
Please help me resolve my issue.
First of all, most of the answers posted here are just off the topic. I have been working with selenium 2 and selenium 3 now, the webdriver can handle window scroll to make an element visible.
For everyone posting snippets like:
driver.execute_script('scrollBy(0, 250)')
you do not get the question at all!
Actually I still did not find a way to properly simulate the drag action of scroll handle but this answer seems promising -- but I did not try.
So so far personally there are two ways to do this for me:
Use Keys.ARROW_DOWN
Use Keys.PAGE_DOWN
Actually there is a third way, just give up selenium and contact the website if they provide any API.
The easiest way to do that is executing a Javascript to scroll the element up/down.
JavascriptExecutor jsExec = (JavascriptExecutor) driver;
jsExec.executeScript("document.getElementById('id').scrollDown += 100");
driver.get("http://www.***.com/");
driver.manage().window().maximize();
WebElement scroll = driver.findElement(By.id("someId"));
scroll.sendKeys(Keys.PAGE_DOWN);
Scroll Down:
import org.openqa.selenium.JavascriptExecutor;
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(0, 250)"); //y value '250' can be altered
Scroll up:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(250, 0)"); //x value '250' can be altered
Scroll bottom of the Page:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));");
or
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys(Keys.END).perform();
Full scroll to bottom in slow motion:
for (int second = 0;; second++) {
if(second >=60){
break;
}
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,400)", ""); //y value '400' can be altered
Thread.sleep(3000);
}
or
JavascriptExecutor jse = (JavascriptExecutor)driver;
for (int second = 0;; second++) {
if(second >=60){
break;
}
jse.executeScript("window.scrollBy(0,800)", ""); //y value '800' can be altered
Thread.sleep(3000);
}
Scroll automatically to your WebElement:
Point hoverItem =driver.findElement(By.xpath("Value")).getLocation();
((JavascriptExecutor)driver).executeScript("return window.title;");
Thread.sleep(6000);
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,"+(hoverItem.getY())+");");
// Adjust your page view by making changes right over here (hoverItem.getY()-400)
or
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", driver.findElement(By.xpath("Value')]")));
or
WebElement element = driver.findElement(By.xpath("Value"));
Coordinates coordinate = ((Locatable)element).getCoordinates();
coordinate.onPage();
coordinate.inViewPort();
First you should do scroll rather than find element so do like below :
document.getElementById("your div id").scrollTop(250);
After above you can find that specific div.
You can also try below :
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.scrollBy(250,350)");
Another way of doing it using JavascriptExceutor's scrollIntoView() method:
WebElement DIVelement = driver.findElement(By.xpath("xpath to div"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView(true)", DIVelement);
Consider your HTML is like below:
<div id="someId" class="className" style="position: relative; top: 0px; left: opx;>
you can observe style attribute in div
check for the value of top which is 0px in above example
Now try to do something like:
$('.className').animate({top: "-60px"});
which will help you to scroll down.
Its a JavaScript executor so of course you need to implement it.
My 'WORKAROUND' is to scroll to the position by element's x and y co-ordinates. I also added an offset to y so that any header/footer or other element don't block the visibility of the element that I want to scroll to.
I have my answer posted under this question -
Selenium webdriver can't click on a link outside the page
None of the posted answers worked for me, however I have found a solution based on this post.
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollTop=arguments[1].offsetTop",
divWithScrollbarElement,
elementToScrollTo);
where divWithScrollbarElement is the div element which you are looking to scroll, and elementToScrollTo is the child element which you want to make viewable (which in my case was actually the parent of the element which I was initially trying to view). If elementToScrollTo is not actually in the DOM yet, you may need to use the script once to scroll down as far as possible, and then again once more elements have loaded.
As you found, webdriver won't find elements that aren't visible so you need to scroll to the element. However you can't scroll directly to the element because webdriver won't find it until it is visible. Catch-22.
However I do have a way that you can scroll within a DIV. First assign the DIV you want to scroll to an element variable, and then you can use javascript to scroll that element instead of scrolling the entire window.
Some VB.NET example code that should be easily adapted to other languages:
Dim div_to_scroll As IWebElement = driver.FindElement(By.XPath("[put your xpath here]"))
driver.ExecuteJavaScript("arguments[0].scrollBy(0,500)", div_to_scroll)
' Short pause to make sure the screen updates:
System.Threading.Thread.Sleep(500)
If you don't know how far you need to scroll then you will need a loop with a test to see if the desired element is visible yet. This isn't a particularly elegant or fast way of doing things but webdriver isn't a fast solution to begin with and I have found this method to be very robust.
Just in case for anyone looking for an alternative solution, here I put mine using python, which should be easy to transform to Java. First, I was using:
more = panel.find_elements(By.CSS_SELECTOR, "//li")
self.driver.execute_script("arguments[0].scrollIntoView();", more[-1])
if last == more[-1]:
break
else:
last = more_followers[-1]
#wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "//li")))
time.sleep(0.5)
in a loop for a ul inside a div. However, the more li elements appear, the slowest was selenium to perfom this action. At the end, because the div containing the ul had a unique class name I used the following in a loop:
while num_of_il<num_of_elements:
self.driver.execute_script("document.getElementsByClassName('myclass')[0].scrollTop += 100;");
time.sleep(0.5)
num_of_il = self.driver.execute_script("return document.getElementsByTagName('li').length")
print("Num of li "+str(num_of_il))
This way is not slow anymore, and with the 0.5 I give enough time to load my next entries. You can also have other getElementsBy as getElementById(), getElementsByName(), getElementsByTagName() and getElementsByTagNameNS(). Look methods at https://developer.mozilla.org/en-US/docs/Web/API/document/ You can check the number of elements loaded accessing the num_of_il variable. Consider introducing some code to break the loop in case num_of_il does not change (e.g. end of items reached).

How do I scroll down vertically in a specific div in a web page

I have searched all the forums but I didn't get a correct answer for my issue. My web page to test has a link hidden below, and I am trying to find it manually by searching for it with xpath or the ID attribute of the element, but I am not able to find it when I am running the web driver script. Even when it is not giving any error on that element, I am getting an error on next command/line.
I found below code from the forums, which is scrolling whole page. I don't want this, I want to scroll down vertically in a specific div area as in screen shot.
JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript("ctl00_Menu1_scrollDiv.scrollBy(0,250)", "");
div id for this is "ctl00_Menu1_scrollDiv"
Element id: ctl00_Menu1_DlMenu_ctl09_LnkMenuname
Please help me on this issue. Thanks in advance.
Help will be appreciated.
This is umendra tomar , I have found very simple solution for this, please use the below code for scroll a specific div in html using selenium .
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.getElementById('scrollCustom').scrollTop= 450");
scrollCustom = this is the ID of your div which you want to scroll.
document.getElementById = this is use in javascript to locate a webelement.
Don't worry we can use this in java using javascriptExecutor
Check if this works for you.
var s = $('#ctl00_Menu1_scrollDiv').scrollTop();
This will give the current value of the scroll in the div.Use this only if you want to scroll inside a div to a certain point dynamically. Otherwise you can hardcode the scrollTop value inside animate()
Using the current value of your scroll you can parameterize the given below scrollTop parameter
$("#ctl00_Menu1_scrollDiv").animate({ scrollTop: "100px" }); // Here 100 px is just an example
I had used this to scroll a large div programmatically in my webdriver framework. Also, this will work if your AUT has jQuery loaded in the browser.
In Java:
JavascriptExecutor js;
js = (JavascriptExecutor) driver;
js.executeScript("$(\"#ctl00_Menu1_scrollDiv\").animate({ scrollTop: \"100px\" })");
First you should not just reference an element by the id. You should set scrollTop to scroll it to a position.
document.getElementById("ctl00_Menu1_scrollDiv").scrollTop(250);
Non-JQuery solution based on this post.
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollTop=arguments[1].offsetTop",
divWithScrollbarElement,
elementToScrollTo);
where divWithScrollbarElement is the div element which you are looking to scroll, and elementToScrollTo is the child element which you want to make viewable (which in my case was actually the parent of the element which I was initially trying to view). If elementToScrollTo is not actually in the DOM yet, you may need to use the script once to scroll down as far as possible, and then again once more elements have loaded.

Categories

Resources