Unable to use keyDown and keyUp events using selenium Webdriver - selenium-webdriver

I want to do the following, can someone help me what wrong i have done..
1) open the site mentioned in code
2) Enter the Text "WELcoME" (mixture of capital and small letters) using keydown and keyup events in webdriver.
public class KeysUpandDown {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://fleet.idrivesafely.com");
driver.manage().window().maximize();
driver.findElement(By.linkText("Student Login")).click();
WebElement loc=driver.findElement(By.className("input1"));
Actions a= new Actions(driver);
a.moveToElement(loc)
.keyDown(Keys.SHIFT)
.sendKeys("wel")
.keyUp(Keys.SHIFT)
.sendKeys("co")
.keyDown(Keys.SHIFT)
.sendKeys("me");
a.perform();
}
}

Your code requires 2 small changes.
Change 1:
WebElement loc=driver.findElement(By.className("input1"));
is pointing to three Web-elements on the page, Instead use below
WebElement loc=driver.findElement(By.xpath("//input[#class='input1' and #name='pin_no']"));
Change 2: Its a Text field, so Instead of
a.moveToElement(loc)
Use
a.click(loc)
So you code should be as below :
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://fleet.idrivesafely.com");
driver.manage().window().maximize();
driver.findElement(By.linkText("Student Login")).click();
WebElement loc=driver.findElement(By.xpath("//input[#class='input1' and #name='pin_no']"));
Actions a= new Actions(driver);
a.click(loc).keyDown(Keys.SHIFT).sendKeys("wel").keyUp(Keys.SHIFT).sendKeys("co").keyDown(Keys.SHIFT).sendKeys("me").perform();

Related

Multiple screenshot using selenium webdriver

What are the steps to take multiple screenshots in selenium without updating the previous screenshot?
Use this:
class Main {
public static void main(String [] args) throws Exception {
WebDriver driver = new ChromeDriver(); driver.manage().window().maximize();
driver.get("irctc.co.in/");
Date d =new Date();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("E:\\selenium\\screenshot\\"+d.toString().replace(":", "_")+".png"));
}
}

Is there any way to enter data in text field without giving webelement

I need to send data on the highlighted tab, but don't want to pass data by findElement. My code is listed below. Please advise.
public class A003_KeyBoardActions {
public static void main(String[] args) throws Exception{
System.setProperty("WebDriver.driver","C:eclipse\\IEDriverServer.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("URL");
Robot r=new Robot();
r.keyPress(java.awt.event.KeyEvent.VK_TAB);
r.keyRelease(java.awt.event.KeyEvent.VK_TAB);
System.out.println("Cursor moved to home page");
r.keyPress(java.awt.event.KeyEvent.VK_TAB);
r.keyRelease(java.awt.event.KeyEvent.VK_TAB);
System.out.println("Courser moved to username");
**HERE I NEED TO SEND DATA ON HIGHLIGHTED TAB** I dont want to pass data by
findElement.
Thread.sleep(1000);
driver.close();
}
}
You can do something like this.
String userName = "YourGoodName";
StringSelection stringSelection = new StringSelection(userName);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);

Explicit wait is not working for Firefox (52.4.0 (64-bit))

Explicit wait is not working for Firefox (52.4.0 (64-bit))below is my code:
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://XXXX/XXXXX/XX/login");
driver.findElement(By.id("userId")).sendKeys("XXXXX");
driver.findElement(By.id("password")).sendKeys("XXXXX");
driver.findElement(By.id("submit")).click();
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//span[text()='Viewer']")));
driver.findElement(By.xpath("//span[text()='Viewer']")).click();
}
I have to use Explicit wait here in any case as elements doesn't get loaded in fixed time. I have searched lot in google but didn't find any code working for me.
As per your code attempt it seems you are waiting for the WebElement through WebDriverWait and then trying to invoke click() method. In your code you have used the clause presenceOfElementLocated with ExpectedConditions, which as per the documentation doesn't confirms if the WebElement is Displayed and Enabled as well.
A better solution will be to modify the clause for ExpectedConditions where instead of presenceOfElementLocated we have to use elementToBeClickable as follows:
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Viewer']")));
You are using presenceOfElementLocated. As per documentation:
An expectation for checking that an element is present on the DOM of a
page. This does not necessarily mean that the element is visible.
You have to be sure that you are waiting on the element the correct expected condition.
as per #DebanjanB , i just it is not an good idea to use presenceOfElementLocated instead it is always better to use elementToBeClickable so correct code should be:
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://XXXX/XXXXX/XX/login");
driver.findElement(By.id("userId")).sendKeys("XXXXX");
driver.findElement(By.id("password")).sendKeys("XXXXX");
driver.findElement(By.id("submit")).click();
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Viewer']")));
driver.findElement(By.xpath("//span[text()='Viewer']")).click();
}

Selenium - Reduce findelement time

When I run the webdriver it runs too fast.
The webdriver is moving the next element before the first one appears.
Can I make webdriver slower?
Thanks!
If you are using java, you can do implicit waits on every page found here
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
but a better way of doing this is by using fluent waits, to wait for a element to appear on the page, like this
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo;
};
and you can use it by
WebElement element = fluentWait(By.id("name"));
element.click();
This is a great answer to read over answer to waits with selenium

Alert doesn't close using Selenium WebDriver with Google Chrome.

I have the following Selenium script for opening alert on rediff.com:
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[#id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
Thread.sleep(5000);
Alert alert=driver.switchTo().alert();
alert.accept();
}
}
This very same script is working fine in Firefox and IE9, however using Google Chrome after opening the alert, rest of the code is not working. The main thing is that does not shows any exception, error or anything.
Please provide any solution as soon as possible.
Thanks a lot!
Note: If we need to change any setting of browser or any thing please let me know.
Selenium version:Selenium(2) Webdriver
OS:Windows 7
Browser:Chrome
Browser version:26.0.1410.64 m
I'm pretty sure your problem is a very common one, that's why i never advise using Thread.sleep(), since it does not guarantee the code will run only when the Alert shows up, also it may add up time to your tests even when the alert is shown.
The code below should wait only until some alert is display on the page, and i'd advise you using this one Firefox and IE9 aswell.
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 5);
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[#id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
}
}
Mostly all that is done here, is changing Thread.sleep(), for a condition that actually will only move forward on the code as soon a alert() is present in the page. As soon as someone does, it wil switch to it and accept.
You can find the Javadoc for the whole ExpectedConditions class here.
Unfortunately AlertIsPresent doesn't exist in C# API
http://selenium.googlecode.com/git/docs/api/dotnet/index.html
You can use something like this:
private static bool TryToAcceptAlert(this IWebDriver driver)
{
try
{
var alert = driver.SwitchTo().Alert();
alert.Accept();
return true;
}
catch (Exception)
{
return false;
}
}
public static void AcceptAlert(this IWebDriver driver, int timeOutInSeconds = ElementTimeout)
{
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOutInSeconds)).Until(
delegate { return driver.TryToAcceptAlert(); }
);
}

Resources