Use Selenium with same browser session - testing

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;
}
}

Related

Getting org.openqa.selenium.ElementNotInteractableException error

Here is my program below on running it I'm getting an error org.openqa.selenium.ElementNotInteractableException.
In this program, I am trying to test a login page with 4 different sets of data using DataProvider annotation so my script is running
Chrome gets initiated
website gets open
click and enter username and password
And the above three steps happen for each set of data provided.
But still on the completion of the whole thing, I'm getting this error. Please help!
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import basePage.*;
//Login to edureka website
public class myPorfileupdate
{
WebDriver driver1;
#Test (dataProvider ="edulogin")
public void myLogin(String username, String password) throws IOException, InterruptedException
{ AppTest a =new AppTest();
driver1 = a.initializeDriver();
driver1.findElement(By.xpath("//span[#data-button-name='Login']")).click();
driver1.findElement(By.xpath("//input[#type='email']")).clear();
driver1.findElement(By.xpath("//input[#type='email']")).sendKeys(username);
driver1.findElement(By.xpath("//input[#type='password']")).sendKeys(password);
driver1.findElement(By.xpath("//*[#id=\"new_sign_up_optim\"]/div/div/div[2]/div[3]/form/button")).click();
Thread.sleep(1000);
driver1.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try{
WebElement d= driver1.findElement(By.linkText("Trending Courses"));
System.out.println(d);
}
catch (Exception Ex){
// Get text displayes on login page
System.out.println("Userid/password is incorrect");
}
}
#DataProvider(name="edulogin")
public Object[][] testData() {
Object[][] data = new Object[4][2];
data[0][0] = "ambika97.singh#gmail.com";
data[0][1] = "Omsairam#1234";
//2nd row
data[1][0] = "abc";
data[1][1] = "Omsairam#1234";
//3rd row
data[2][0] = "ambika97.singh#gmail.com";
data[2][1] = "xyz";
//4th row
data[3][0] = "abc";
data[3][1] = "xyz";
return data;
}
}```
**First two lines of my console are**
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation.

How to run the testng test methods parallel?

I am trying to run the test methods in parallel by using TestNg concept, but it's not working as expected. It's launching multiple browsers and creating each thread for each browser, but it's entering all the value in only one browser. Please help me out. Here browser object and extent reports object are thread safe. Please find the test methods.
This is the Test class that needs to be executed in parallel, but it's not working. It just launches multiple browsers and all the thread value feeding data to one browser itself.
package com.sonata.tests;
import java.util.Map;
import java.util.Properties;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.sonata.utility.DataReader;
import com.sonata.utility.DriverCreation;
import com.sonata.pages.ComplaintPage;
import com.sonata.pages.HomePage;
import com.sonata.pages.LoginPage;
public class ComplainTest extends DriverCreation {
private String browser;
private String url;
HomePage homeObject;
LoginPage loginObject;
ComplaintPage compObject;
DataReader dataReader = new DataReader();
#Parameters({ "url", "browser" })
#BeforeMethod
public void readProperties(String url, String browser) {
/*
* Properties prop = PropertiesReader.getProperty(); browser =
* prop.getProperty("browser.name"); url = prop.getProperty("app.url");
*/
this.browser = browser;
this.url = url;
}
#Test
public void createComplaintCaseWithDefault() {
setTestCaseName("TC-10672");
initExtent(testCaseName);
if (!dataReader.isTestCaseExecute(xlsReader, testCaseName)) {
logger.info("Test Case not executed as its run mode is NO");
throw new SkipException("");
}
Object[][] testData = dataReader.getTestData(xlsReader, testCaseName);
for (int t = 0; t < testData.length; t++) {
initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
#SuppressWarnings("unchecked")
Map<String, String> testDataMap = (Map<String, String>) testData[t][0];
loginObject = new LoginPage(driver, report, wait, logger);
loginObject.login(testDataMap.get("UserName"),
testDataMap.get("Password"));
compObject = new ComplaintPage(driver, report, wait, logger);
compObject.createCase(testDataMap.get("ComplaintType"),
testDataMap.get("CustomerName"),
testDataMap.get("ComplaintCategory"));
compObject.complaintPageVerification();
}
}
#Test
public void createComplaintCaseWithSensitive() {
setTestCaseName("TC-10692");
initExtent(testCaseName);
if (!dataReader.isTestCaseExecute(xlsReader, testCaseName)) {
logger.info("Test Case not executed as its run mode is NO");
throw new SkipException("");
}
Object[][] testData = dataReader.getTestData(xlsReader, testCaseName);
for (int t = 0; t < testData.length; t++) {
initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
#SuppressWarnings("unchecked")
Map<String, String> testDataMap = (Map<String, String>) testData[t][0];
loginObject = new LoginPage(driver, report, wait, logger);
loginObject.login(testDataMap.get("UserName"),
testDataMap.get("Password"));
compObject = new ComplaintPage(driver, report, wait, logger);
compObject.createCase(testDataMap.get("ComplaintType"),
testDataMap.get("CustomerName"),
testDataMap.get("ComplaintCategory"));
compObject.complaintPageVerification();
}
}
#Test
public void reopenComplaintFieldVerfication() {
setTestCaseName("TC-10958");
initExtent(testCaseName);
if (!dataReader.isTestCaseExecute(xlsReader, testCaseName)) {
logger.info("Test Case not executed as its run mode is NO");
throw new SkipException("");
}
Object[][] testData = dataReader.getTestData(xlsReader, testCaseName);
for (int t = 0; t < testData.length; t++) {
initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
#SuppressWarnings("unchecked")
Map<String, String> testDataMap = (Map<String, String>) testData[t][0];
loginObject = new LoginPage(driver, report, wait, logger);
loginObject.login(testDataMap.get("UserName"),
testDataMap.get("Password"));
compObject = new ComplaintPage(driver, report, wait, logger);
compObject.reopenReasonFieldVerification(testDataMap
.get("ComplaintID"));
}
}
#AfterMethod
public void closeBrowser() {
if (driver != null) {
homeObject.tearDownTest();
}
if (report != null) {
report.endTest();
}
}
}
This is the Driver class which will create the driver instance for each Test method.
package com.sonata.utility;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.LogStatus;
import com.sonata.constants.Constants;
public class DriverCreation {
public ExtentReports report;
public WebDriver driver;
public DesiredCapabilities cap1;
public WebDriverWait wait;
protected String testCaseName;
ExtentReport extent;
public Logger logger = Logger.getLogger(this.getClass().toString());
public ExcelReader xlsReader = new ExcelReader(getProjectPath()
+ Constants.XLS_FILE_PATH);
/*
* public DriverCreation(String browser,ExtentReports report,Logger logger){
* this.browser = browser; this.report = report; this.logger = logger; }
*/
public void initExtent(String reportName) {
extent = new ExtentReport();
report = extent.getExtentReportInstance(reportName);
}
public void setTestCaseName(String testCaseName){
this.testCaseName = testCaseName;
}
public WebDriver initDriver(String browser) {
try {
cap1 = new DesiredCapabilities();
if (!Constants.CONSTANTS_GRIDEXECUTION) {
if (browser.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver",
Constants.CONSTANTS_GECKO_DRIVER_PATH);
cap1.setCapability("marionette", true);
/* ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new FirefoxDriver(cap1);
}
};*/
//driver = driver1.get();*/
driver= new FirefoxDriver(cap1);
driver.manage().timeouts()
.implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO, "Firefox driver has started");
logger.info("Firefox driver has started");
} else if (browser.equalsIgnoreCase("Chrome")) {
System.setProperty(Constants.CONSTANTS_CHROME_PROPERTY,
Constants.CONSTANTS_CHROME_DRIVER_PATH);
/*driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new ChromeDriver();
}
};
driver = driver1.get();*/
driver = new ChromeDriver();
driver.manage().timeouts()
.implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO, "Chrome driver has started");
logger.info("Chrome driver has started");
} else if (browser.equalsIgnoreCase("PhantomJS")) {
System.setProperty(Constants.CONSTANTS_PHANTOM_PROPERTY,
Constants.CONSTANTS_PHANTOM_DRIVER_PATH);
cap1.setJavascriptEnabled(true);
cap1.setCapability("takesScreenshot", true);
cap1.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
Constants.CONSTANTS_PHANTOM_DRIVER_PATH);
/*ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new PhantomJSDriver(cap1);
}
};
driver = driver1.get();*/
driver = new PhantomJSDriver(cap1);
driver.manage().window().setSize(new Dimension(1920, 1200));
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO,
"PhantomJS/Ghost driver has started");
logger.info("PhantomJS/Ghost driver has started");
} else if (browser.equalsIgnoreCase("IE")) {
System.setProperty(Constants.CONSTANTS_IE_PROPERTY,
Constants.CONSTANTS_IE_DRIVER_PATH);
// cap1.internetExplorer();
cap1.setCapability(
InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION,
true);
/*ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new InternetExplorerDriver(cap1);
}
};
driver = driver1.get();*/
driver = new InternetExplorerDriver(cap1);
driver.manage().timeouts()
.implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO,
"Internet Explorer driver has started");
logger.info("Internet Explorer driver has started");
}
} else {
String nodeUrl = Constants.CONSTANTS_IPDETAILS;
if (browser.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver",
Constants.CONSTANTS_GECKO_DRIVER_PATH);
cap1.setCapability("marionette", true);
cap1 = DesiredCapabilities.firefox();
cap1.setBrowserName("firefox");
cap1.setPlatform(Platform.WINDOWS);
} else if (browser.equalsIgnoreCase("Chrome")) {
System.setProperty(Constants.CONSTANTS_CHROME_PROPERTY,
Constants.CONSTANTS_CHROME_DRIVER_PATH);
cap1 = DesiredCapabilities.chrome();
cap1.setBrowserName("chrome");
cap1.setPlatform(Platform.WINDOWS);
} else if (browser.equalsIgnoreCase("IE")) {
System.setProperty(Constants.CONSTANTS_IE_PROPERTY,
Constants.CONSTANTS_IE_DRIVER_PATH);
// cap1.internetExplorer();
cap1 = DesiredCapabilities.internetExplorer();
cap1.setBrowserName("internet explorer");
cap1.setPlatform(Platform.WINDOWS);
cap1.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
cap1.setCapability(
InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION,
true);
}
ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
try {
return new RemoteWebDriver(new URL(nodeUrl), cap1);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
};
driver = driver1.get();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO, browser + " driver has started");
logger.info(browser + " driver has started");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Assert.assertTrue(true, "Set up Test");
} catch (Exception e) {
logger.error("Try and catch block while assert " + e);
}
}
return driver;
}
private String getProjectPath() {
File currentDirFile = new File("");
String path = currentDirFile.getAbsolutePath();
return path;
}
}
TESTNG SUITE XML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="C4C" thread-count="3" parallel="methods">
<parameter name="url" value="https://abc.xyz.ondemand.com/"/>
<parameter name="browser" value="Chrome"/>
<test name="Case" allow-return-values="true" group-by-instances="true">
<classes>
<class name="com.sonata.tests.ComplainTest" >
</class>
</classes>
</test>
</suite>
You are storing the driver at class level. But you parallelise based on methods. In this case one driver object will be there. I see the thread local lines were commented.
There are two ways to solve this issue,
One: As your running in method level and navigating the HomePage in each method, you can maintain driver object in method level,
Webdriver driver = initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
Other way: you can maintain the driver object in thread local in your driver creation class,
public class DriverCreation {
private static ThreadLocal<WebDriver> WEBDRIVER = new ThreadLocal<WebDriver>();
public WebDriver getWebDriver(String browser){
WebDriver driver= WEBDRIVER.get();
if (driver== null) {
driver = initDriver(browser);
WEBDRIVER.set(driver);
}
return driver;
}
}
And use it in test method in same way,
Webdriver driver = getWebDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
The second one will create only one driver per thread while first one will create one driver per method. Handle the driver quit accordingly

Selenium sendkeys ctrl+5 is not working

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

how to get the number of busy selenium hub slots

Is there a way to get the number of busy slots on a selenium hub?
I only know the hub console url (/grid/console), there I can parse the html code ... but this is quite ugly, and quite slow if there are many slots.
Maybe somebody knows a better way?
thanks,
Alex.
This is an old question but perhaps this solution help others.
You can extend org.openqa.grid.web.servlet.RegistryBasedServlet, inject it to the hub and get information via http/json
This is the code for the class:
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.internal.ProxySet;
import org.openqa.grid.internal.Registry;
import org.openqa.grid.internal.RemoteProxy;
import org.openqa.grid.internal.TestSlot;
import org.openqa.grid.web.servlet.RegistryBasedServlet;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public class NodesInfoServlet extends RegistryBasedServlet {
private static final long serialVersionUID = -5559403361498232207L;
public NodesInfoServlet() {
super(null);
}
public NodesInfoServlet(Registry registry) {
super(registry);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
process(req, resp);
}
protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(200);
JsonObject res;
try {
res = getFreeBrowsers();
response.getWriter().print(res);
response.getWriter().close();
} catch (JsonIOException e) {
throw new GridException(e.getMessage());
}
}
private JsonObject getFreeBrowsers() throws IOException, JsonIOException {
JsonObject requestJSON = new JsonObject();
ProxySet proxies = this.getRegistry().getAllProxies();
JsonObject platformsbrowsers = new JsonObject();
for (RemoteProxy proxy : proxies) {
for (TestSlot slot : proxy.getTestSlots()) {
if (slot.getSession() == null){
// Plataforma del slot
Platform ptf = getPlatform(slot);
if (ptf != null){
JsonArray browserlist = new JsonArray();
if (!platformsbrowsers.has(ptf.toString())){
platformsbrowsers.add(ptf.toString(), browserlist);
}
JsonArray platform = platformsbrowsers.getAsJsonArray(ptf.toString());
// Browser del slot
DesiredCapabilities cap = new DesiredCapabilities(slot.getCapabilities());
JsonPrimitive browser = new JsonPrimitive(cap.getBrowserName());
if (!platform.contains(browser)){
platform.add(browser);
}
}
}
}
}
requestJSON.add("PlatformsBrowsers", platformsbrowsers);
return requestJSON;
}
private static Platform getPlatform(TestSlot slot) {
Object o = slot.getCapabilities().get(CapabilityType.PLATFORM);
if (o == null) {
return Platform.ANY;
} else {
if (o instanceof String) {
return Platform.valueOf((String) o);
} else if (o instanceof Platform) {
return (Platform) o;
} else {
throw new GridException("Cannot cast " + o + " to org.openqa.selenium.Platform");
}
}
}
}
You need to inject in the hub:
java -classpath C:\Selenium\selenium-server-standalone.jar;C:\Selenium\NodesInfoServlet.jar; org.openqa.grid.selenium.GridLauncher -role hub -hubConfig hubConfig.json -servlets NodesInfoServlet
You get the results via http:
http://localhost:4444/grid/admin/NodesInfoServlet
Result:
{
PlatformsBrowsers: {
VISTA: [
"internet explorer",
"phantomjs",
"htmlunit"
]
}
}
Hope this helps!!!
What I researched so far, the Selenium API is not providing a method to get the hub information from the client side. It is pretty ugly to parse the source code but that is working for me. Other people mentioned to make some changes to the selenium hub jar file but that won't be scalable and it will be needed with each selenium version. (Firefox versions and Selenium versions are all the time changing... I wouldn't recommend you to do that)
If you are using Java, you can try to use Json simple to parse the string and get easily the browsers.
https://code.google.com/p/json-simple/
I hope this can be helpful.

How to verify whether a link read from file is present on webpage or not?

I am new at automation. I have to write a code as follow
I have to read around 10 url's from a file and store it into one hashtable then I need to read one by one url's from hashtable and while iterating through this url I also need to read one more file conataining 3 url's and search them on webpage . If present need to click that link
I have written following code but I am not getting the logic for checking whether a link from file is present on webpage or not...
Please check my code and help me to solve/improve it.
Main test script
package com.samaritan.automation;
import java.util.Hashtable;
import java.util.Set;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FirstScript {
WebDriver driver = new FirefoxDriver();
String data;
CommonControllers commonControll = null;
Hashtable<String, String> recruiters = null;
#Test
public void script() throws Exception {
CommonControllers commonControll = new CommonControllers();
recruiters = new Hashtable<String,String>();
recruiters = commonControll.readDataFromFile("D:/eRecruiters/_Recruiters.properties");
Set<String> keys = recruiters.keySet();
for(String key: keys){
/**HERE I NEED TO WRITE THE FUNCTION TO VERIFY WHETHER THE LINK READ FROM SECOND FILE IS PRESENT ON WEBPAGE OR NOT**/
}
}
}
and function to read from file into hashtable
public Hashtable<String, String> readDataFromFile(String fileName) {
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String strLine = null;
String []prop = null;
while((strLine = br.readLine()) != null) {
prop = strLine.split("\t");
recruiters.put(prop[0], prop[1]);
}
br.close();
fr.close();
}catch(Exception exception) {
System.out.println("Unable to read data from recruiter file: " + exception.getMessage());
}
return recruiters;
}
PLease take a look! thanks
Priya...You can use
if(isElementPresent(By.linkText(LinkTextFoundFromFile))){
//code when link text present there
}else {
//code for not finding the link
}
Now the following method is generalized for any By object you can use like By.xpath, By.id etc.
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}