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

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.

Related

Page Object Patern in Java Selenium - update of elements

I use Page Object Pattern in Java Selenium and I've got problem with updating element after click action.
There is a list of X elements on page and button that enables to scroll them (after clicking on button, new elements are displayed on the list, old ones disappear)
There are two classes:
public abstract class WebPage {
protected WebDriver driver;
WebPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(new AppiumFieldDecorator(driver, Duration.ofSeconds(30)), this);
}
and
public class ChildClass extends WebPage{
#FindBy(selector)
List<WebElement> elements;
By nextButton = By.id(xxx);
ChildClass(WebDriver driver) {
super(driver);
}
public void iterateAllElements(){
for (WebElement element: elements){
//some action
}
if(buttonIsEnabled())
clickOnButton();
iterateAllElements();
}
}
Please tell me why object "elements" is not initialized with new values after invoking clickOnButton(); function? I cannot get elements that are displayed on 2nd, 3rd page ect
There are still elements from 1st view on the list. It works fine in debug mode, but problem occurs when I want to run it.

How To Automate Slider in Selenium Java

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

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

In Moneycontrol's Login page , Selenium is unable to find the Webelementes

In Moneycontrol's website, I am unable to enter the username and password while trying to log in. Selenium is unable to find the Webelements.
public void setUrl() throws IOException {
driver = new FirefoxDriver()
driver.get("http://www.moneycontrol.com/");
}
public void Login() {
driver.findElement(By.xpath("//a[#title='Log In']")).click();
//enter user name and password
driver.findElement(By.xpath("//div[#class='formbox']/div[1]/form/div[1]")).sendKeys("xyz#gmail.com");
driver.findElement(By.xpath("//input[#id='pwd']")).sendKeys("Abc#92");
screenshot
The Email or User ID field is within an <iframe>, so to invoke sendKeys() at Email or User ID and Password field you have to switch to the respective <iframe> as follows :
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[#src='https://accounts.moneycontrol.com/mclogin/?d=2']")));
driver.findElement(By.xpath("//form[#id='login_form']//input[#class='textfield' and #id='email']")).sendKeys("xyz#gmail.com");
driver.findElement(By.xpath("//form[#id='login_form']//input[#class='textfield' and #id='pwd']")).sendKeys("Abc#92");
**Selenium with C#**
You need to switch to frames and in your case id of your frame is "myframe". Below is the working code for selenium with C#
[TestMethod]
public void moneyControl()
{
IWebDriver driver = new ChromeDriver(#"C:\Users\Akash\Downloads\chromedriver_win32\");
driver.Navigate().GoToUrl("http://www.moneycontrol.com/");
driver.Manage().Window.Maximize();
driver.FindElement(By.XPath("//a[#title='Log In']")).Click();
driver.SwitchTo().Frame("myframe");
driver.FindElement(By.Id("email")).SendKeys("xyz#gmail.com");
driver.FindElement(By.Id("pwd")).SendKeys("abc");
}

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();`
}
}