How To Automate Slider in Selenium Java - selenium

Hi I am trying to automate https://emicalculator.net/
.I tried many approach but did not get success Below is my code for automating Interest rate slider
package seleniumBasics;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class AdjustSliderValue {
static String baseUrl = "https://emicalculator.net/";
public static WebDriver driver;
#BeforeTest
public WebDriver createDriver() {
driver = DriverSetup.getWebDriver();
driver.get(baseUrl);
return driver;
}
#AfterMethod
public void CloseDriver() {
driver.quit();
}
public static int GetPixelsToMove(WebElement Slider, double Amount, double SliderMax, double SliderMin) {
int pixels = 0;
int tempPixels = Slider.getSize().getWidth();
System.out.println(tempPixels);
tempPixels = (int)(tempPixels / (SliderMax - SliderMin));
System.out.println(tempPixels);
tempPixels = (int) (tempPixels * (Amount - SliderMin));
System.out.println(tempPixels);
pixels = tempPixels;
return pixels;
}
#Test
public static void verifySlider() throws InterruptedException {
WebElement Slider = driver.findElement(By.xpath("//*[#id=\"loaninterestslider\"]"));
int PixelsToMove = GetPixelsToMove(Slider, 15, 20, 5);
Actions SliderAction = new Actions(driver);
SliderAction.clickAndHold(Slider).moveByOffset((-(int) Slider.getSize().getWidth() / 2), 0)
.moveByOffset(PixelsToMove, 0).release().perform();
}
}
I want a method which can automate any slider. Could any one who knows please help me. Thanks in advance.

You may also try Key actions using Send Keys
// Set Loop counter to get desired value
<Your_Slider_Element>.sendKeys(Keys.ARROW_LEFT); // Or ARROW_RIGHT
// End loop

dragAndDropBy usually work best with slider. Make sure the way you calculate pixel is correct then it good to go.
driver.get("https://emicalculator.net/");
WebElement Slider = driver.findElement(By.xpath("//*[#id=\"loaninterestslider\"]"));
int PixelsToMove = GetPixelsToMove(Slider, 15, 20, 5);
Actions move = new Actions(driver);
Action action = (Action) move.dragAndDropBy(Slider, PixelsToMove, 0).build();
action.perform();
Import package
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

Sliderwidth is basically just 100% of the size here but you can add whatever pixel you want.
driver.get("https://emicalculator.net/");
WebElement Slider = driver.findElement(By.xpath("//*[#id=\"loaninterestslider\"]"));
Dimension sliderSize = Slider.getSize();
int sliderWidth = sliderSize.getWidth();
int xCoord = Slider.getLocation().getX();
Actions builder = new Actions(driver);
builder.moveToElement(Slider)
.click()
.dragAndDropBy
(Slider,xCoord + sliderWidth, 0)
.build()
.perform();
Import
import org.openqa.selenium.Dimension;
import org.openqa.selenium.interactions.Actions;

WebDriver driver = new ChromeDriver();
driver.get("https://emicalculator.net/");
WebElement a = driver.findElement(By.cssSelector("#loanamountslider span"));
Actions action = new Actions(driver);
action.clickAndHold(a).moveByOffset(500, 0).perform();
Here you go , you have to click the slider element and drag it

As the topicstarter correctly mentioned, the question is about how to automate any slider. So let me extend existing answers with requested solution.
The solution is not new - Selenium already has sample with Select. Let's build similar solution.
So assume we wanted to have some object of type EmiSlider so we could use it the way:
...
EmiSlider slider = new EmiSlider(driver.findElement(By.id("loanamountslider")));
slider.slide(100);
...
We are explicitly mentioning the desired locator and passing into constructor of class EmiSlider. The EmiSlider class then would be:
public class EmiSlider {
private final WebElement sliderRoot;
private final WebDriver driver;
public EmiSlider(WebElement slider) {
// Simply store passed root WebElement
this.sliderRoot = slider;
// We require driver instance for internal use so resolve it and store
this.driver = ((WrapsDriver) slider).getWrappedDriver();
}
/**
* Moves slider left or right
* #param x pixels to move slider by. Positive value moves right, negative - left
*/
public void slide(int x) {
// Find the slider WebElement, which is child of root element, using relative search
WebElement sliderElement = this.sliderRoot.findElement(By.cssSelector("span"));
// Perform slide action
new Actions(this.driver)
.clickAndHold(sliderElement)
.moveByOffset(x, 0)
.release()
.perform();
}
}
The current slider implementation had few drawbacks:
It does not count on the current and extreme positions
Different sliders might have different scales (and they do)
The amout inputs are left alone while
Hope one can add missed functionality

Related

ControlsFx - Spreadsheetview - DateCell - keep editing on failure

we use a spreadsheetview with different kind of cell types.
In the documentation to SpreadsheetCellEditor we found the following text:
The policy regarding validation of a given value is defined in
SpreadsheetCellType.match(Object). If the value doesn't meet the requirements
when saving the cell, nothing happens and the editor keeps editing.
now we facing the following problem:
if you enter "abcd" in an integer cell as a wrong entry and push enter key, nothing happens. Editor is still in edit mode. This is exactly the behaviour as descripted in the documentation. that is what we want.
if you have a date cell and enter a wrong date or something else and push enter key, cell stops editing mode and set value return to "old" value.
how can we prevent this behaviour?
Maybe its a bug in the Date SpreadsheetCellType?
we use a lot of custom cellType Classes, but the behaviour is also comprehensibly with this little example.
I hope everything is well explained.
Thanks for your help.
import java.time.LocalDate;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.controlsfx.control.spreadsheet.GridBase;
import org.controlsfx.control.spreadsheet.SpreadsheetCell;
import org.controlsfx.control.spreadsheet.SpreadsheetCellType;
import org.controlsfx.control.spreadsheet.SpreadsheetView;
public class SpreadSheetExample extends Application {
private SpreadsheetView getSpreadSheet() {
SpreadsheetView spreadSheetView;
GridBase grid;
grid = new GridBase(10, 2);
spreadSheetView = new SpreadsheetView(grid);
ObservableList<ObservableList<SpreadsheetCell>> rows = FXCollections.observableArrayList();
for (int row = 0; row < grid.getRowCount(); ++row) {
final ObservableList<SpreadsheetCell> list = FXCollections.observableArrayList();
for (int column = 0; column < grid.getColumnCount(); ++column) {
if (column < 1) {
list.add(SpreadsheetCellType.DATE.createCell(row, column, 1, 1, LocalDate.now()));
} else {
list.add(SpreadsheetCellType.INTEGER.createCell(row, column, 1, 1, column));
}
}
rows.add(list);
}
spreadSheetView.getColumns().forEach((column) -> {
column.setPrefWidth(280);
});
grid.setRows(rows);
return spreadSheetView;
}
#Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.getChildren().add(getSpreadSheet());
Scene scene = new Scene(root, 800, 400);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Update:
are there no controlsfx experts?
Solved:
https://groups.google.com/forum/#!topic/controlsfx-dev/ro7-MvLFD1A
It is solved.
i got some help from one of the major contributor of ControlsFX.
The documentation was a bit unclearly.
In order to get the described behavior, a custom Cell Type + Editor based on the existing ones can be created.
For all details take a look in this thread:
https://groups.google.com/forum/#!topic/controlsfx-dev/ro7-MvLFD1A

How should I use WebElements and Actions through page object model?

I have a button on my Webpage which I want to click once the required piece of information is entered. I am currently using By to establish all the elements of the page but want to use WebElements for this button and then use Actions to click it later.
How should I do that in my Page Object class.
I tried with below approach :
WebElement addressinput = driver.findElement(By.xpath("//input[#id='pac-input']"));
By addressinput = By.xpath("//input[#id='pac-input']");//this works fine
But on running the Test class as TestNG it shows null pointer exception on WebElement line. Tried to do it with By as well but the button just won't recieve the click. It works pefectly fine with WebElements and action which I have tried before without using POM below is the reference code for that :
WebElement button = driver.findElement(By.xpath("//button[#id='btn_gtservice']"));
Actions action = new Actions(driver);
action.moveToElement((WebElement) CheckAvailability).click().perform();
driver.switchTo().defaultContent();
You've got
action.moveToElement((WebElement)CheckAvailability)
That should be
action.moveToElement((button)CheckAvailability)
As it is, you'll be getting a null pointer as you have no variable named WebElement defined
When using PageFactory in PageObjectModel if you expect the element to be loaded after some information is entered, through some JavaScript and it might not be immediately present on the page already you can use the Actions once the element is returned through WebDriverWait support with a normal locator factory as follows:
Code Block:
package com.pol.zoho.PageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.interactions.Actions;
public class ZohoLoginPage {
WebDriver driver;
public ZohoLoginPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//button[#id='btn_gtservice']")
public WebElement myButton;
public void doLogin(String username,String userpassword)
{
WebElement button = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(ZohoLoginPage.getWebElement()));
new Actions(driver).moveToElement(button).click().perform();
}
public WebElement getWebElement()
{
return myButton;
}
}
You can find a detailed discussion in How to use explicit waits with PageFactory fields and the PageObject pattern

Not able to identify element on the screen- how to use tab

Screenshot of the element I want to click:
I automating my website(new to automation). once i login i get to another page where selenium web driver is not able to find any of the elements(I tried all possibilities even sso related).
Only solution i could find was using tabs and enter.
So when i enter that page i need to click 9 time "TAB" key from the keyboard and then enter so that my login is verified. since i don't have any element using which i can perform the tab and enter actions. is there a way where once i get to that page the web driver starts pressing "TAB" key 9 times and then "Enter" on 10 time.
Please help I have been working on this over a week now and not getting
anywhere.
optimist_creeper-main class:
package Modules;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import Modules.HomePage;
public class MainClass {
String appUrl = "als-stg-1.mtvn.ad.viacom.com/webqa/";
#Test public void MainTest() {
System.setProperty("webdriver.gecko.driver", "C:\\Shayni Coding\\Automation\\Gecko\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get(appUrl);
HomePage home = new HomePage();
home.HomePageTest(driver);
}
}
Home Page class:
public class HomePage {
#BeforeClass public void beforeClass() {
System.out.println("before class");
}
public void HomePageTest(WebDriver driver) {
driver.manage().window().maximize();
WebElement email = driver.findElement(By.id("cred_userid_inputtext"));
email.sendKeys("shayni#outlook.com");
WebElement pass = driiver.findElement(By.id("cred_password_inputtext"));
pass.sendKeys(Keys.ENTER);
pass.click();
String expectedTitle = "VMS Web";
String actualTitle = driver.getTitle();
Assert.assertEquals(expectedTitle,actualTitle);
}
}
Thanks.
Just get a random object like the body tag and use that to send your key presses.
e.g.
WebElement dummyElement = driver.findElement(By.xpath("/html/body"));
for (int i = 0; i < 9; ++i) {
dummyElement.sendKeys(keys.TAB);
}
dummyElement.sendKeys(keys.ENTER);
The above code finds the body take and sets it as an element. It then presses the tab key 9 times and then presses the enter key. Which is what you asked for. Hope that helps.

Java3D and Behaviours : KeyNavigatorBehaviour works fine, but not MouseRotate

I don't manage to give user mouse interaction to a ColorCube by using a MouseRotate. However, when i use a KeyNavigatorBehaviour, i can control the cube with keyboard as needed.
Here the code i used to test MouseRotate :
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.GraphicsConfigTemplate3D;
import javax.media.j3d.TransformGroup;
import javax.swing.JFrame;
import javax.vecmath.Point3d;
import com.sun.j3d.exp.swing.JCanvas3D;
import com.sun.j3d.utils.behaviors.mouse.MouseRotate;
import com.sun.j3d.utils.geometry.ColorCube;
import com.sun.j3d.utils.universe.SimpleUniverse;
public class MovingAroundCube extends JFrame {
private static final long serialVersionUID = 1L;
public MovingAroundCube(){
setTitle("Moving around cube");
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JCanvas3D jCanvas3D = new JCanvas3D(new GraphicsConfigTemplate3D());
jCanvas3D.setSize(300, 300);
add(jCanvas3D);
SimpleUniverse universe = new SimpleUniverse(jCanvas3D.getOffscreenCanvas3D());
universe.getViewingPlatform().setNominalViewingTransform();
universe.addBranchGraph(createSceneGraph());
}
public BranchGroup createSceneGraph() {
BranchGroup objRoot = new BranchGroup();
TransformGroup listenerGroup = new TransformGroup();
listenerGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
listenerGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
objRoot.addChild(listenerGroup);
//KeyNavigatorBehavior behaviour = new KeyNavigatorBehavior(listenerGroup);
MouseRotate behaviour = new MouseRotate(listenerGroup);
behaviour.setSchedulingBounds(new BoundingSphere(new Point3d(), 100));
listenerGroup.addChild(behaviour);
listenerGroup.addChild(new ColorCube(0.4));
return objRoot;
}
public static void main(String[] args) {
new MovingAroundCube().setVisible(true);
}
}
If I uncomment the line creating the KeyNavigatorBehaviour and comment the line creating the MouseRotate, user interaction this time is possible .
So, why can't the cube react to the mouse (when i use MouseRotate behaviour instance) ?
Any help will be appreciated.
System : Xubuntu 11.04
Java3D version : 1.5.2
There are two ways to solve this dilemma:
Use this constructor:
MouseRotate behaviour = new MouseRotate(jCanvas3D, listenerGroup);
or
Enable mouse events as long as no MouseListeners are added:
import java.awt.AWTEvent;
JCanvas3D jCanvas3D = new JCanvas3D(new GraphicsConfigTemplate3D()) {
{
this.enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK |
AWTEvent.MOUSE_WHEEL_EVENT_MASK);
}
};
Key events are enabled because 'setFocusable(true)' is set in JCanvas3D.
August, InteractiveMesh

Refresh is not working using sendkeys ,Selenium JAVA

I am trying to automate google search,normal sendkeys is working ,but when I try to send using keys.F5 or ascii code ,refresh wont work
also when try to do location reload it gives error as " The method execute_script(String) is undefined for the type WebDriver
"
Tried instead of F5 ,F1 key also but no avail
` package com.at.sample;
import org.openqa.selenium.Keys;
import java.lang.Thread;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
// import org.openqa.selenium.Alert;
import java.util.List;
public class Refreshgoogle {
public static void main(String[] args) throws InterruptedException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver","c://chromedriver.exe");
driver= new ChromeDriver();
//Launch the Application Under Test (AUT)
driver.get("http://google.com");
Actions action = new Actions(driver);
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("test data");
//sends normal keybaord strokes
// approch 1 driver.findElement(By.xpath("//html")).sendKeys(Keys.F5);
// approch 2.1 WebElement element1 = driver.findElement(By.xpath("//*[#id=\"tsf\"]/div[2]/div[1]/div[2]/div[2]"));
//approch 2.2 element1.sendKeys(Keys.F1);
// approch 3 driver.findElement(By.xpath("//*[#id=\"gsr\"]")).sendKeys(Keys.F5);
// driver.execute_script("location.reload(true);");
System.out.println(driver.getTitle());
// working driver.navigate().to(driver.getCurrentUrl());
}
}
`
There are 4 approaches
First 3 wont refresh pagea
when used 4th it shows error as The method execute_script(String) is undefined for the type WebDriver
You can refresh in below ways:
1.Using get method and recursive way
driver.get("https://URL.com");
driver.get(driver.getCurrentURL());
Using Navigate method and Recursively calling your URL
driver.get("https://URL.com");
driver.navigate.to(driver.getCurrentURL());
Using one valid webelement and send keys
driver.get("https://URL.com");
driver. findElement(By.id("username")).sendKeys(Keys.F5);
Hope this help.
Please refer below solution
driver.navigate.refresh();
If you want to refresh your page using keys then you can also use Robot class.
Robot robot = new Robot(); // Robot class throws AWT Exception
Thread.sleep(2000); // Thread.sleep throws InterruptedException
robot.keyPress(KeyEvent.VK_CONTROL); // press Control key down key of
robot.keyPress(KeyEvent.VK_F5);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_F5);
Thread.sleep(2000);
This is selenium related issue more details available here: https://github.com/webdriverio/webdriverio/issues/1344
WebElement(I) sendKeys() will not accept Keys (keyboard keys). This can be handled using Actions class only.
Additionally, if you need to refresh the page, use WebDriver() refresh() or get current URL using getCurrentUrl() of same interface and navigate() using same url as parameter.
Update:
Here is the detailed explanation on each approach:
1) As per 'https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebElement.html#sendKeys-java.lang.CharSequence...-', sendKeys() in WebElement(I) accepts only char sequence (i.e. string.).
// approch 1 driver.findElement(By.xpath("//html")) returns a WebElement and this element sendKeys will accept only char sequence. Hence, your approach r=to refresh using Keys.F5 won't work here.
2) // approch 2.1 WebElement element1 = driver.findElement(By.xpath("//*[#id=\"tsf\"]/div[2]/div[1]/div[2]/div[2]"));
//approch 2.2 element1.sendKeys(Keys.F1);
Same explanation as approach 1.
3) // approch 3 driver.findElement(By.xpath("//*[#id=\"gsr\"]")).sendKeys(Keys.F5);
Did the same kind of operation as approach 1 and is explained there.
4) If we need to use javascriptexecutor, first we need to create javascriptexecutor object like below and should call execute_script() using reference variable of that object:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
If you are not created this object, you will get 'execute_script(String) is undefined for the type WebDriver', which is expected.
Hence, the 4 approaches what you tried will not refresh the page.
Instead, you can use below options:
1) Actions class sendKeys(): which will accept keyboard keys.
2) using driver.navigate().refresh();
3) Using javascriptexecutor after creating an object for the same (as explained in approach 4)
Try with this code:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class TestRefresh {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
`// case 1:`
`driver.navigate().to(driver.getCurrentUrl());`
`// case 2:`
`((JavascriptExecutor)driver).executeScript("document.location.reload()");`
`// case 3:`
`driver.navigate().refresh();`
}
}