I have a requirement wherein
I need to invoke F12 developer tool in IE.
Navigate to profiler tab.
start profiler
I am using IE 9. In the below code, I am trying to navigate by entering ctrl5. It is not working.
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.HasInputDevices;
import org.openqa.selenium.interactions.Keyboard;
import org.testng.annotations.Test;
import org.openqa.selenium.remote.DesiredCapabilities;
public class InvokeIEbrowser {
#Test
public void IEdriver() {
System.setProperty("webdriver.ie.driver",
"D:\\2015\\softwares\\IEDriverServer_x64_2.48.0\\IEDriverServer.exe");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
capabilities.setCapability("ACCEPT_SSL_CERTS", true);
WebDriver driver = new InternetExplorerDriver();
/*
Keyboard keyboard = ((HasInputDevices) driver).getKeyboard();
keyboard.sendKeys(Keys.F12);
*/
/*
driver.get("http://mail.yahoo.com");
System.out.println(driver.getTitle());
*/
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//driver.FindElement(By.XPath("String")).SendKeys(Keys.NumberPad5);
//keyboard.sendKeys(Keys.CONTROL);
//getKeyboard().sendKeys(Keys.CONTROL, Keys.F5);
Actions actionObject = new Actions(driver);
actionObject.sendKeys(Keys.F12).perform();
//actionObject.sendKeys(Keys.CONTROL).sendKeys(Keys.NUMPAD5).keyUp(Keys.CONTROL).perform();
actionObject.sendKeys(Keys.CONTROL.NUMPAD5).perform();
System.out.println("done");
}
}
You could try using Keys.chord() (more about it here):
driver.FindElement(By.XPath("String")).SendKeys(Keys.chord(Keys.CONTROL, Keys.NUMPAD5 ));
or by using the Action class and the unicode representation:
Actions action = new Actions();
action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0035')).perform();
You can find more references about the unicode representation here.
Are you just trying to send the hotkey to the page? Try an extension of driver...
public static void sendCtrl5(this IWebDriver Driver)
{
Driver.FindElement(By.TagName("body")).Click(); // make window active
new Actions(Driver)
.SendKeys(Keys.Control + Keys.NumberPad5)
.Perform();
}
Use: driver.sendCtrl5();
Related
I'm trying to automate Sign In functionality in www.sears.com, but could not recognize the Email text field using the below code
package com.bigbasket.framework.lab;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Sears {
public static void main(String[] args) {
WebDriver browser = new FirefoxDriver();
browser.get("http://www.sears.com/en_us.html");
browser.manage().window().maximize();
browser.findElement(By.xpath("//*[#id='gnf_01_tree_item_5']/span/a")).click();
WebElement currentElement = browser.findElement(By.xpath("//*[#id='myProfiles']/div"));
Actions actions = new Actions(browser);
actions.moveToElement(currentElement).build().perform();
browser.findElement(By.xpath("//*[#id='subnavDD_myProfile']/ul/li[1]/p/a")).click();
try{
WebElement formElement = browser.findElement(By.id("loginFormDisplay"));
currentElement = formElement.findElement(By.xpath("//*[#id='email']"));
}catch(Exception e){
System.out.println(e.getMessage());
}
WebDriverWait wait = new WebDriverWait(browser, 30);
wait.until(ExpectedConditions.visibilityOf(currentElement));
currentElement.sendKeys("srinimarva#gmail.com");
browser.quit();
}
}
Could you please help me in resolving this? Apologize I'm an amateur in Selenium WebDriver for asking a silly question.
your email field is in iframe so to access it you need to switch to frame first, following is the working code for your issue :
WebDriver browser = new FirefoxDriver();
browser.get("http://www.sears.com/en_us.html");
browser.findElement(By.xpath("//*[#id='gnf_01_tree_item_5']/span/a")).click();
WebElement currentElement = browser.findElement(By.xpath("//*[#id='myProfiles']/div"));
Actions actions = new Actions(browser);
actions.moveToElement(currentElement).build().perform();
WebDriverWait wait = new WebDriverWait(browser, 10);
wait.until(ExpectedConditions.visibilityOf(browser.findElement(By.xpath(".//*[#id='subnavDD_myProfile']/ul/li[1]/p/a"))));
browser.findElement(By.xpath(".//*[#id='subnavDD_myProfile']/ul/li[1]/p/a")).click();
try{
WebElement frameElement = browser.findElement(By.xpath(".//iframe[contains(#name, 'easyXDM_default')]"));
browser.switchTo().frame(frameElement);
}
catch(Exception e){
System.out.println(e.getMessage());
}
browser.findElement(By.name("email")).sendKeys("srinimarva#gmail.com");
browser.quit();
I am a newbie to selenium testing.
Basically,
I have a selenium class like :
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import java.awt.AWTException;
import java.awt.Robot;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumTests {
public void commonFunction(){
System.setProperty("webdriver.chrome.driver", "C://Downloads//chromedriver_win32//chromedriver.exe");
WebDriver driver = new ChromeDriver();
Actions builder = new Actions(driver);
driver.get("http://localhost:3000");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
test1(driver,builder);
}
//The driver,builder will be used by all the below 3 test functions.
/**
* Calling the Most Visited API -- TEST1
*/
public void test1(WebDriver driver,Actions builder){
WebElement most_visited_link = driver.findElement(By.id("mostVisited"));
Thread.sleep(2000);
Action mouseOvermost_visited_link = builder.moveToElement(most_visited_link).build();
mouseOvermost_visited_link.perform();
Thread.sleep(2000);
driver.findElement(By.id("mostVisited")).click();
Thread.sleep(1000);
WebElement most_Visited_button = driver.findElement(By.id("datePicked"));
Action mouse_most_VisitedOverDatePicker = builder.moveToElement(most_Visited_button).build();
mouse_most_VisitedOverDatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
test2(driver,builder);
}
/**
* Calling the Status Pie API -- TEST2
* #param builder
* #param driver
*/
public void test2(WebDriver driver,Actions builder){
WebElement status_pie_link = driver.findElement(By.id("statusPie"));
Thread.sleep(2000);
//Actions builder = new Actions(driver);
Action mouseOverStatusPie = builder.moveToElement(status_pie_link).build();
mouseOverStatusPie.perform();
Thread.sleep(1000);
driver.findElement(By.id("statusPie")).click();
Thread.sleep(1000);
WebElement status_pie_button = driver.findElement(By.id("datePicked"));
Action mouseOver_Status_pie_DatePicker = builder.moveToElement(status_pie_button).build();
mouseOver_Status_pie_DatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
test3(driver,builder);
}
/**
* Calling the Old Data API -- TEST3
*/
public void test2(WebDriver driver,Actions builder){
WebElement old_data_link = driver.findElement(By.id("oldData"));
Thread.sleep(2000);
// Actions builder = new Actions(driver);
Action mouseOverOldData = builder.moveToElement(old_data_link).build();
mouseOverOldData.perform();
Thread.sleep(2000);
driver.findElement(By.id("oldData")).click();
Thread.sleep(1000);
WebElement old_data_button = driver.findElement(By.id("datePicked"));
Action mouseOverDatePicker = builder.moveToElement(old_data_button).build();
mouseOverDatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
driver.quit();
}
}
The code executes as expected on the browser and closes the chrome window.
However, in the index report, I see log as :
3 methods, 2 skipped, 1 passed
Skipped methods :
mostVisitedfunction
statuspiefunction
Passed methods :
createConnection
Any idea where am I going wrong ?
Thanks in advance.
The method mostVisitedfunction should not have annotation because it is the helping method for yoyr test case. Instead create a new class, create a object of the same in the #test class and then call that method..
See the below example..
My test is
//MAximize the Screen
driver.manage().window().maximize();
//Go to Gmail Login Page
SignInPage SignInPage = WebUtils.GoToSignInPage(driver);
//Sign in to Login page -Send Username
SignInPage.SendkeysMethodForSignInPAge(driver, By.cssSelector("input[id='Email']") , "kishanpatelllll.8#gmail.com" );
//Click on Next
SignInPage.ClickToLogin(driver, By.cssSelector("input[id='next']"));
//Wait for password field to be visible
SignInPage.WaitForElementTobeVisible(driver, By.cssSelector("input[id='Passwd'][type='password']"));
So when i call the method SendkeysMethodForSignInPAge i wont write it in #Test.
See SendkeysMethodForSignInPAge method:
public class SignInPage {
public void SendkeysMethodForSignInPAge(WebDriver driver, By by, String s) {
WebUtils.Sendkeys(driver,by,s);
}
I created a new class and there i defined it.
This is basic flow.
Hope you can relate this.
Reply to me, if your are still stuck.
Happy Learning :-)
The error comes because if you have parameters in your #Test annotated method, then those need to come from #Parameters or #DataProvider. Else, if none of the annotation supplies the arguments, which is your case, then the error is thrown.
Apart from that what #Kishan has suggested in terms of structure of code is correct. You need to differentiate between your tests and common functions.
#Test
public void assertBackToLogin(WebDriver driver) throws InterruptedException {
LoginPage login = new LoginPage (driver);
login.assertLogin();
}
Is NOT working
Remove all the parameters and run
#Test
public void assertBackToLogin() throws InterruptedException {
LoginPage login = new LoginPage (driver);
login.assertLogin();
}
So I want to automate youtube videos. so list of API available and also selenium have support for flash objects. My worry is that how can I check video is playing?. Like if I can perform motion detect on video I can pass or fail script accordingly. so can we achieve similar using selenium? or selenium have different approach to do this. Many thanks
I would check that when they click on the 'play' button it changes to the 'pause' icon; something like this:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
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.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
public class Youtube {
public WebDriver driver;
private String url = "https://www.youtube.com/watch?v=MfhjkfocRR0";
public Youtube() {
System.setProperty("webdriver.chrome.driver", "C:\\SeleniumServer\\chromedriver.exe");
driver = new ChromeDriver();
//driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get(url);
}
public void waitFor(int wait){
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public boolean isYoutubePlaying(){
try {
//wait 4 secs for Youtube video to load
waitFor(6000);
WebElement playPauseButton=driver.findElements(By.cssSelector("div.ytp-button")).get(0);
//video is not playing here.
if(playPauseButton.getAttribute("aria-label").equals("Play")){
System.out.println("This Youtube video wasn't playing but we clicked on it to play the video.");
//so we click on the play button to play the video then we return true;
playPauseButton.click();
return true;
}else{
//video should be playing but let's double-check
if(playPauseButton.getAttribute("aria-label").equals("Pause")){
System.out.println("Youtube video is already playing.");
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
//only return false if either of the 2 cases above fail.
return false;
}
}//end class
And to run this code simply instantiate it like so:
Youtube yt=new Youtube();
yt.isYoutubePlaying();
Run the below script properly that time not moved any other area but if perform any action I mean move to any other area that time my download file code not work.
Is the issue related to focus or need some changes. using firefox 21 version browser and selenium 2.33. Please suggest.
Here is the code:
package mypackage;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.junit.Before;
import org.junit.Test;
import Data.Function;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.After;
public class Report extends Function {
Object Open_a_popup_window;
String Positioned_Popup ;
Object JavaScript_Popup_Windows ;
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "my url";
}
#Test
public void Report1() throws Exception {
Function object = new Function();
object.Login();
/* Enter Report Details */
driver.get(baseUrl + "//");
driver.get(baseUrl + "//");
/*Run*/
driver.findElement(By.xpath("")).click();
Thread.sleep(30000);
WebElement Action = driver.findElement(By.xpath(""));
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
((JavascriptExecutor) driver).executeScript("window.focus();");}
String linktxt = Action.getText();
if (linktxt.equalsIgnoreCase("Record not found.")) {
System.out.println("Report contains No Data:");
}
if (linktxt.equalsIgnoreCase("FAILED")) {
System.out.println("Report failed");
} else {
driver.findElement(By.xpath("/img")).click();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(10000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(10000);
System.out.println("Report Passed");
}
}
}
#After
public void teardown() {
driver.close();
//System.exit(0);
}
}
I see you've used Robot with pressing Enter, and of course it'll work on the window which has the focus!
So once you moves out, the enters are fired on the newly focused window.
The pop up window was browser pop which was not handled by robot keys, so i used third party app "auto it" but it has limitation only used for windows operating system , not supported by unix or linux .
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
public class Test1 {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.ie.driver", "D:/Development/ProgrammingSoftware/Testing/IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
baseUrl = "http://seleniumhq.org/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test1() throws Exception {
driver.get(baseUrl + "/download/");
driver.findElement(By.linkText("Latest Releases")).click();
driver.findElement(By.linkText("All variants of the Selenium Server: stand-alone, jar with dependencies and sources.")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
I would like to have the IE with the same session but this code opens always a new instance of IE. How I get this work?
I don't think it is possible to attach driver to an existing session.
If You've done executing a test method and if you want to execute another test method which is present in another class or package, call the method by passing the present driver to it so that you can use the present instance of the driver over there.
This question has been asked several times in the past and the one I'm about to answer is not even close to recent. However I still gonna go ahead and post an answer because recently I've been engulfed with questions related to same browser session. How would I be able to leverage the browser which is already open, so I can continue my test run, rather than restart it from the scratch. It's even painstaking in some cases, after navigating through tons of pages, when you encounter the issue of restarting your Selenium test. Instead I was left wondering "where is the silver bullet?". Finally I saw one of the articles written by "http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/". However still there are a few missing links. So I wanted to unravel it here with the help of a suitable example.
In the following code snippet, I'm trying to launch SeleniumHQ and Clicking Download link in a Selenium session in Chrome browser.
System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
//First Session
ChromeDriver driver = new ChromeDriver();
HttpCommandExecutor executor = (HttpCommandExecutor)
driver.getCommandExecutor();
URL url = executor.getAddressOfRemoteServer();
SessionId session_id = driver.getSessionId();
storeSessionAttributesToFile("Id",session_id.toString());
storeSessionAttributesToFile("URL",url.toString());
driver.get("https://docs.seleniumhq.org/");
WebElement download = driver.findElementByLinkText("Download");
download.click();
If you read the above code, I'm capturing the URL of Selenium remote server and the session id of the current selenium (browser) session and writing it to a properties file.
Now if I need to continue executing in the same browser window/session, despite stopping the current test run, all I need to do is comment the code below the commented First session in the aforementioned code snippet and continuing your tests from the code below:
System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
//First Session
//ChromeDriver driver = new ChromeDriver();
//HttpCommandExecutor executor = (HttpCommandExecutor) driver.getCommandExecutor();
//URL url = executor.getAddressOfRemoteServer();
//SessionId session_id = driver.getSessionId();
//storeSessionAttributesToFile("Id",session_id.toString());
// storeSessionAttributesToFile("URL",url.toString());
// driver.get("https://docs.seleniumhq.org/");
// WebElement download = driver.findElementByLinkText("Download");
// download.click();
//Attaching to the session
String existingSession = readSessionId("Id");
String url1 = readSessionId("URL");
URL existingDriverURL = new URL(url1);
RemoteWebDriver attachToDriver = createDriverFromSession(existingSession, existingDriverURL);
WebElement previousReleases = attachToDriver.findElementByLinkText("Previous Releases");
previousReleases.click();
Now you may have to refactor and rename the driver object (even leaving the name would still work, but I just wanted to differentiate between attaching it to an existing driver and the launching the driver). In the above code block, I continue my tests, after reading and assigning the URL and sessionid and create the driver from session to continue leveraging the browser and session.
Please view the complete code below:
package org.openqa.selenium.example;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Collections;
import java.util.Properties;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
import org.openqa.selenium.remote.http.W3CHttpResponseCodec;
public class AttachingToSession {
public static String SESSION_FILE = "C:\\example\\Session.Properties";
public static Properties prop = new Properties();
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
//First Session
ChromeDriver driver = new ChromeDriver();
HttpCommandExecutor executor = (HttpCommandExecutor) driver.getCommandExecutor();
URL url = executor.getAddressOfRemoteServer();
SessionId session_id = driver.getSessionId();
storeSessionAttributesToFile("Id",session_id.toString());
storeSessionAttributesToFile("URL",url.toString());
driver.get("https://docs.seleniumhq.org/");
WebElement download = driver.findElementByLinkText("Download");
download.click();
//Attaching to the session
String existingSession = readSessionId("Id");
String url1 = readSessionId("URL");
URL existingDriverURL = new URL(url1);
RemoteWebDriver attachToDriver = createDriverFromSession(existingSession, existingDriverURL);
WebElement previousReleases = attachToDriver.findElementByLinkText("Previous Releases");
previousReleases.click();
}
public static RemoteWebDriver createDriverFromSession(final String sessionId, URL command_executor){
CommandExecutor executor = new HttpCommandExecutor(command_executor) {
#Override
public Response execute(Command command) throws IOException {
Response response = null;
if (command.getName() == "newSession") {
response = new Response();
response.setSessionId(sessionId);
response.setStatus(0);
response.setValue(Collections.<String, String>emptyMap());
try {
Field commandCodec = null;
commandCodec = this.getClass().getSuperclass().getDeclaredField("commandCodec");
commandCodec.setAccessible(true);
commandCodec.set(this, new W3CHttpCommandCodec());
Field responseCodec = null;
responseCodec = this.getClass().getSuperclass().getDeclaredField("responseCodec");
responseCodec.setAccessible(true);
responseCodec.set(this, new W3CHttpResponseCodec());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
response = super.execute(command);
}
return response;
}
};
return new RemoteWebDriver(executor, new DesiredCapabilities());
}
public static void storeSessionAttributesToFile(String key,String value) throws Exception{
OutputStream output = null;
try{
output = new FileOutputStream(SESSION_FILE);
//prop.load(output);
prop.setProperty(key, value);
prop.store(output, null);
}
catch(IOException e){
e.printStackTrace();
}
finally {
if(output !=null){
output.close();
}
}
}
public static String readSessionId(String ID) throws Exception{
Properties prop = new Properties();
InputStream input = null;
String SessionID = null;
try {
input = new FileInputStream(SESSION_FILE);
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty(ID));
SessionID = prop.getProperty(ID);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return SessionID;
}
}