Selenium objects out of the screen - selenium

I currently have a selenium test that runs smooth on 1920 * 1080 resolution.
But I have a task to make this test on different common resolutions such as
1366 *768.
Problem is when I run my Selenium test on smaller resolutions than 1920 * 1080 I can't find some elements that is below the window (as expected)
How do I solve this?
I've tried
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));");
To scroll to the bottom of the page but with no success.
Would appreciate help loads.
Using java, Selenium, TestNG and POM.

Hi to scroll please use like below
Scrolling to bottom of a page
driver.navigate().to(URL);
((JavascriptExecutor) driver)
.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Scrolling to an element on a page
driver.navigate().to(URL);
WebElement element = driver.findElement(By.id("id"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView();", element);
Scrolling by coordinates
driver.navigate().to(URL);
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");

to scroll bottom of page, use the below code:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0,300)", "");
or
js.executeScript("scroll(0, 300);");
or
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

Related

Unable to switch to iframe using Selenium Webdriver

I am trying to learn the feature drag and drop in the webpage
Link
The Section Books is inside the iframe.
But i am unable to access the iframe I am getting below error
no such element: Unable to locate element:
Below are the Xpath i tried
// WebElement frame =driver.findElement(By.xpath("//div[#id='root']//iframe[#class='st-preview-body']"));
// WebElement frame =driver.findElement(By.tagName("iframe"));
WebElement frame =driver.findElement(By.xpath("//iframe[#src='https://snippet.webixcode.com/snippet.html?0.0.3']"));
driver.switchTo().frame(frame);
I also tried using by.id and also xpath using id and class name
What will be the mistake i am doing? To my knowledge there is only one iframe present
The code for drag and drop. will this work?
WebElement fromdrag=driver.findElement(By.xpath("//span[#class='dhx_tree-list-item__text'][normalize-space()='Lawrence Block']"));
WebElement todrop=driver.findElement(By.id("treeTarget"));
Actions act=new Actions(driver);
act.dragAndDrop(fromdrag, todrop).build().perform();
Its a Nested iframe. We need to switch to those iframes one by one to access Elements from All Books.
The page takes time to load, better apply Explicit waits to find the Elements. And you also need to driver.switchTo().defaultContent(); to come out of the iframe and find Elements outside the iframe
public void iframequestion() {
System.setProperty("webdriver.chrome.driver","C:\\expediaproject\\Chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor)driver;
driver.get("https://dhtmlx.com/docs/products/dhtmlxTree/");
WebElement frame1 = driver.findElement(By.xpath("//iframe[#src='https://snippet.dhtmlx.com/3e0b5r57?mode=mobile']"));
js.executeScript("arguments[0].scrollIntoView(true);", frame1);
driver.switchTo().frame(frame1);
WebElement frame2 = driver.findElement(By.xpath("//iframe[#class='st-preview-body']"));
driver.switchTo().frame(frame2);
WebElement frame3 = driver.findElement(By.id("content"));
driver.switchTo().frame(frame3);
WebElement ele1 = driver.findElement(By.xpath("//span[text()='Fiction & Fantasy']"));
System.out.println(ele1.getText());
driver.switchTo().defaultContent();
WebElement ele2 = driver.findElement(By.xpath("//a[text()='View more demos']"));
System.out.println(ele2.getText());
driver.quit();
}
Fiction & Fantasy
View more demos

Scrollby method in selenium

I have used the below code for scroll down.
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,1250)", "");
How do you calculate the pixel values when you want to scroll the window to a specific point ?
I guess you are trying to scroll to some element.
what you can do is:
WebElement e = driver.findElement(....);
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView(true);", e);

How to scroll down the page till bottom(end page) in the Selenium WebDriver

I need to scroll down page till end in the Selenium WebDriver. I tried to scroll down the page by using the following code snippet:
JavascriptExecutor jse6 = (JavascriptExecutor) driver;
jse6.executeScript("window.scrollBy(0,250)", "");
It's being scrolled but I need to scroll down till end page.
We have to use JavascriptExecutor
To scroll using coordinate
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");
To scroll till end of the page
((JavascriptExecutor) driver)
.executeScript("window.scrollTo(0, document.body.scrollHeight)");
To scroll till any element
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView();", element);
do it with python,
import time
time.sleep(2)
drive.execute_script("window.scrollTo(0, document.body.scrollHeight)")
based on #shubham bansal's
For this you can take the xpath of any object at the end of the page manually.And use the below code.
WebElement lastElement =
driver.findElement(By.xpath("//a[#title='org.apache.spark download']"));
int y = lastElement.getLocation().getY();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollTo(0,"+y+")");
Thread.sleep(3000);

Popup scroll not working in selenium webdriver

I am running my script in mozilla firefox I want to scroll popup I
applied so many methods but doesn't work for me
I used keys.tab to reach that element but it was unable to enter text in that textfield using senkeys("xyz#gmail.com)
I used scroll method
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('youama-email').scrollIntoView(true);");
some exception occur
3.I used Moveto element method but got exception
WebElement element = driver.findElement(By.id("youama-email"));
Actions
actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.perform();
// Initialize Javascript executor
JavascriptExecutor js = (JavascriptExecutor) driver;
// Scroll inside web element vertically (e.g. 100 pixel)
js.executeScript("arguments[0].scrollTop =
arguments[1];",driver.findElement(By.id("<div-id>")), 100);
Please help me to scroll and enter into the email as well as other
fields that will appear after scroll [![enter image description
here][1]][1]
[1]: http://i.stack.imgur.com/D0hqI.png
Try this code. I think what you didn't do was to wait for the element to be visible which i did. See the below code. It is running correctly.
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://wyomingvapor.com/");
driver.findElement(By.xpath(".//*[#id='header']/div/div[2]/div/a[1]")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='y-to-register']/input")));
driver.findElement(By.xpath(".//*[#id='y-to-register']/input")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='youama-firstname']")));
driver.findElement(By.xpath(".//*[#id='youama-firstname']")).sendKeys("xyz#gmail.com");
Thread.sleep(2000L);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_X);
robot.keyRelease(KeyEvent.VK_X);
robot.keyPress(KeyEvent.VK_Y);
robot.keyRelease(KeyEvent.VK_Y);
robot.keyPress(KeyEvent.VK_Z);
robot.keyRelease(KeyEvent.VK_Z);
If you still stuck then do reply to me, Jyotsana.
Happy Learning :-)

Scroll Element into View with Selenium

Is there any way in either Selenium 1.x or 2.x to scroll the browser window so that a particular element identified by an XPath is in view of the browser? There is a focus method in Selenium, but it does not seem to physically scroll the view in FireFox. Does anyone have any suggestions on how to do this?
The reason I need this is I'm testing the click of an element on the page. Unfortunately the event doesn't seem to work unless the element is visible. I don't have control of the code that fires when the element is clicked, so I can't debug or make modifications to it, so, easiest solution is to scroll the item into view.
Have tried many things with respect to scroll, but the below code has provided better results.
This will scroll until the element is in view:
WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
//do anything you want with the element
You can use the org.openqa.selenium.interactions.Actions class to move to an element.
Java:
WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
Python:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.scrollBy(250,350)");
You may want to try this.
If you want to scroll on the Firefox window using the Selenium webdriver, one of the ways is to use JavaScript in the Java code. The JavaScript code to scroll down (to bottom of the web page) is as follows:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight));");
Targeting any element and sending down keys (or up/left/right) seems to work also. I know this is a bit of a hack, but I'm not really into the idea of using JavaScript to solve the scrolling problem either.
For example:
WebElement.sendKeys(Keys.DOWN);
In Selenium we need to take the help of a JavaScript executor to scroll to an element or scroll the page:
je.executeScript("arguments[0].scrollIntoView(true);", element);
In the above statement element is the exact element where we need to scroll. I tried the above code, and it worked for me.
I have a complete post and video on this:
http://learn-automation.com/how-to-scroll-into-view-in-selenium-webdriver/
webElement = driver.findElement(By.xpath("bla-bla-bla"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);
For more examples, go here. All in Russian, but Java code is cross-cultural :)
I found that the bounding rect of my element was not correct, leading to the browser scrolling well off the screen. However, the following code works rather well for me:
private void scrollToElement(WebElement webElement) throws Exception {
((JavascriptExecutor)webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded()", webElement);
Thread.sleep(500);
}
You can use this code snippet to scroll:
C#
var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();
There you have it
This worked for me:
IWebElement element = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId))[0];
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
Use the driver to send keys like the pagedown or downarrow key to bring the element into view. I know it's too simple a solution and might not be applicable in all cases.
From my experience, Selenium Webdriver doesn't auto scroll to an element on click when there are more than one scrollable section on the page (which is quite common).
I am using Ruby, and for my AUT, I had to monkey patch the click method as follows;
class Element
#
# Alias the original click method to use later on
#
alias_method :base_click, :click
# Override the base click method to scroll into view if the element is not visible
# and then retry click
#
def click
begin
base_click
rescue Selenium::WebDriver::Error::ElementNotVisibleError
location_once_scrolled_into_view
base_click
end
end
The 'location_once_scrolled_into_view' method is an existing method on WebElement class.
I apreciate you may not be using Ruby but it should give you some ideas.
The Ruby script for scrolling an element into view is as below.
$driver.execute_script("arguments[0].scrollIntoView(true);", element)
sleep(3)
element.click
Selenium 2 tries to scroll to the element and then click on it. This is because Selenium 2 will not interact with an element unless it thinks that it is visible.
Scrolling to the element happens implicitly so you just need to find the item and then work with it.
Sometimes I also faced the problem of scrolling with Selenium. So I used javaScriptExecuter to achieve this.
For scrolling down:
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0, 250)", "");
Or, also
js.executeScript("scroll(0, 250);");
For scrolling up:
js.executeScript("window.scrollBy(0,-250)", "");
Or,
js.executeScript("scroll(0, -250);");
This is a repeated solution with JavaScript, but with an added waiting for element.
Otherwise ElementNotVisibleException may appear if some action on the element is being done.
this.executeJavaScriptFunction("arguments[0].scrollIntoView(true);", elementToBeViewable);
WebDriverWait wait = new WebDriverWait(getDriver(), 5);
wait.until(ExpectedConditions.visibilityOf(elementToBeViewable));
I have used this way for scrolling the element and click:
List<WebElement> image = state.getDriver().findElements(By.xpath("//*[contains(#src,'image/plus_btn.jpg')]"));
for (WebElement clickimg : image)
{
((JavascriptExecutor) state.getDriver()).executeScript("arguments[0].scrollIntoView(false);", clickimg);
clickimg.click();
}
def scrollToElement(element: WebElement) = {
val location = element.getLocation
driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}
Something that worked for me was to use the Browser.MoveMouseToElement method on an element at the bottom of the browser window. Miraculously it worked in Internet Explorer, Firefox, and Chrome.
I chose this over the JavaScript injection technique just because it felt less hacky.
You may want to visit page Scroll Web elements and Web page- Selenium WebDriver using Javascript:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FirefoxDriver ff = new FirefoxDriver();
ff.get("http://toolsqa.com");
Thread.sleep(5000);
ff.executeScript("document.getElementById('text-8').scrollIntoView(true);");
}
If you think other answers were too hacky, this one is too, but there is no JavaScript injection involved.
When the button is off the screen, it breaks and scrolls to it, so retry it... ¯\_(ツ)_/¯
try
{
element.Click();
}
catch {
element.Click();
}
In most of the situation for scrolling this code will work.
WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));
js.executeScript("arguments[0].click();",element);
JAVA
Try scroll to element utilize x y position, and use JavascriptExecutor with this is argument: "window.scrollBy(x, y)".
Following import:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
First you need get x y location the element.
//initialize element
WebElement element = driver.findElement(By.id("..."));
//get position
int x = element.getLocation().getX();
int y = element.getLocation().getY();
//scroll to x y
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(" +x +", " +y +")");
I am not sure if the question is still relevant but after referring to scrollIntoView documentation from https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView.
The easiest solution would be
executor.executeScript("arguments[0].scrollIntoView({block: \"center\",inline: \"center\",behavior: \"smooth\"});",element);
This scrolls the element into center of the page.
Javascript
The solustion is simple:
const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);
The default behavior of Selenium us to scroll so the element is barely in view at the top of the viewport. Also, not all browsers have the exact same behavior. This is very dis-satisfying. If you record videos of your browser tests, like I do, what you want is for the element to scroll into view and be vertically centered.
Here is my solution for Java:
public List<String> getBoundedRectangleOfElement(WebElement we)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
List<String> bounds = (ArrayList<String>) je.executeScript(
"var rect = arguments[0].getBoundingClientRect();" +
"return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
System.out.println("top: " + bounds.get(1));
return bounds;
}
And then, to scroll, you call it like this:
public void scrollToElementAndCenterVertically(WebElement we)
{
List<String> bounds = getBoundedRectangleOfElement(we);
Long totalInnerPageHeight = getViewPortHeight(driver);
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}
I've been doing testing with ADF components and you have to have a separate command for scrolling if lazy loading is used. If the object is not loaded and you attempt to find it using Selenium, Selenium will throw an element-not-found exception.
If nothing works, try this before clicking:
public void mouseHoverJScript(WebElement HoverElement) {
String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
((JavascriptExecutor) driver).executeScript(mouseOverScript, HoverElement);
}
In Java we can scroll by using JavaScript, like in the following code:
driver.getEval("var elm = window.document.getElementById('scrollDiv'); if (elm.scrollHeight > elm.clientHeight){elm.scrollTop = elm.scrollHeight;}");
You can assign a desired value to the "elm.scrollTop" variable.
A solution is:
public void javascriptclick(String element)
{
WebElement webElement = driver.findElement(By.xpath(element));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", webElement);
System.out.println("javascriptclick" + " " + element);
}