Throws error when I use TimerTask method and WebDriver - java

In my code, I wanted to do, so that if the test takes more than 10 seconds, the selenium shows the title of the window and closes the window. This code is here:
import java.io.File;
import java.util.Timer;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.os.WindowsUtils;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SanDemoSearch{
public static long czasStart;
public static void main(String[] args) {
czasStart = System.currentTimeMillis();
System.out.println(czasStart);
File file = new File("C:/automatyzacja/IEDriverServer_Win32_2.44.0/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("https://www.google.pl/?gws_rd=ssl");
Narzedzia.disableScreenSaver(driver);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.id("lst-ib")));
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
(new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
WebElement webElement = driver.findElement(By.xpath("//a[#href='http://www.seleniumhq.org/']"));
Assert.assertNotNull("Not found http://www.seleniumhq.org//",webElement);
webElement.click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.findElement(By.id("q")).sendKeys("test",Keys.ENTER);
}
}
and:
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.util.Timer;
import java.util.TimerTask;
import org.openqa.selenium.WebDriver;
public class Narzedzia extends SanDemoSearch{
private static Timer screenSaverDisabler;
public static void disableScreenSaver(final WebDriver driver){
screenSaverDisabler = new Timer();
screenSaverDisabler.scheduleAtFixedRate(new TimerTask() {
Robot r = null;
{
try {
r = new Robot();
} catch (AWTException headlessEnvironmentException) {
screenSaverDisabler.cancel();
}
}
#Override
public void run() {
Point loc = MouseInfo.getPointerInfo().getLocation();
r.mouseMove(loc.x + 1, loc.y);
r.mouseMove(loc.x, loc.y);
long czasEnd = System.currentTimeMillis();
System.out.println(czasEnd);
long difference = (czasEnd - SanDemoSearch.czasStart) / 1000;
System.out.println("difference"+difference);
if(difference > 10){
System.out.println("I can quit application");
driver.getTitle(); //exception: Error 404: Not Found
driver.close();
}
//if()
}
}, 0, 1*1000);
}
}
When I run this code I got error:
Exception in thread "Timer-0" org.openqa.selenium.UnsupportedCommandException: Error 404: Not Found
Not Found
Command duration or timeout: 49 milliseconds
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00'
System info: host: 'SFL000361', ip: '192.168.1.103', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_40'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{browserAttachTimeout=0, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.usePerProcessProxy=false, ignoreZoomSetting=false, handlesAlerts=true, version=10, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:32854/, takesScreenshot=true, javascriptEnabled=true, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=dismiss}]
Session ID: 959f1633-48b4-4bb6-b24d-21a919747655
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:614)
at org.openqa.selenium.remote.RemoteWebDriver.getTitle(RemoteWebDriver.java:313)
at Narzedzia$1.run(Narzedzia.java:35)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
and not always I got error:
Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: session 4b141e0f-b680-4094-92f7-efaa6ea32e75 does not exist
Command duration or timeout: 9 milliseconds
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00'
System info: host: 'SFL000361', ip: '192.168.1.103', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_40'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{browserAttachTimeout=0, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.usePerProcessProxy=false, ignoreZoomSetting=false, handlesAlerts=true, version=10, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:28022/, takesScreenshot=true, javascriptEnabled=true, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=dismiss}]
Session ID: 4b141e0f-b680-4094-92f7-efaa6ea32e75
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:162)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:352)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:393)
at org.openqa.selenium.By$ById.findElement(By.java:214)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at SanDemoSearch.main(SanDemoSearch.java:48)
Problem is with line: driver.getTitle. Selenium didn't see driver?

Follow this link: https://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_Is_WebDriver_thread-safe?
Q: Is WebDriver thread-safe?
A: WebDriver is not thread-safe. Having said that, if you can
serialise access to the underlying driver instance, you can share a
reference in more than one thread. This is not advisable. You /can/ on
the other hand instantiate one WebDriver instance for each thread.
Your code schedules a task using Timer object. Timer class uses another (background) thread to execute it's tasks - it means that two threads are trying to access the same WebDriver instance at the same time.
You can't use the same driver instance among two threads at the same time, because WebDriver is not thread-safe.

Use this code in java
:-
private static final ThreadLocal < WebDriver > webDriver = new ThreadLocal < WebDriver > () {
#Override protected WebDriver initialValue() {
return webdriver.instance;
}
};

Related

Why am I getting org.openqa.selenium.StaleElementReferenceException exception in my code given below?

Hi Everyone I was trying to make a Selenium Script to verify the validations on Username and Password Text Box by fetching the data from Excel file (.xlt format) but whenever i am running my code it is getting the following error after successful loop run . The code is as follows :
package com.selenium.com.selenium.practise;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.testng.annotations.BeforeMethod;
import java.io.File;
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.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
public class MultipleCasesUsingExcel {
public static WebDriver driver = null;
#Test
public void Test() throws BiffException, IOException, InterruptedException {
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Clicking on My Account Link
driver.findElement(By.xpath("//*[#id='top']/body/div/div/div[3]/div/div[4]/ul/li[1]/a")).click();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebElement emailTextBox = driver.findElement(By.xpath("//input[#id='email']"));
WebElement pwdTextBox = driver.findElement(By.xpath("//input[#id='pass']"));
WebElement loginBtn = driver.findElement(By.xpath("//button[#id='send2']"));
Workbook book = Workbook.getWorkbook(new File("C:\\Users\\Umang Bhatia\\Documents\\data.xlt"));
Sheet sheet = book.getSheet(0);
for (int i = 0; i < sheet.getRows(); i++) {
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
for (int j = 0; j < sheet.getColumns() - 1; j++) {
emailTextBox.sendKeys(sheet.getCell(j, i).getContents());
pwdTextBox.sendKeys(sheet.getCell(j + 1, i).getContents());
loginBtn.click();
emailTextBox.clear();
pwdTextBox.clear();
}
Thread.sleep(3000);
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#BeforeMethod
public void beforeMethod() {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Umang Bhatia\\Documents\\Selenium Drivers\\chrome driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://live.guru99.com/index.php/");
}
#AfterMethod
public void afterMethod() {
driver.quit();
}
}
And I am getting the following error after first successful loop run :
[RemoteTestNG] detected TestNG version 6.13.1
Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 36887
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: Test
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=63.0.3239.132)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 31 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'DESKTOP-59DNS54', ip: '192.168.2.5', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\UMANGB~1\AppData\Local\Temp\scoped_dir13984_1984}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=63.0.3239.132, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, setWindowRect=true, unexpectedAlertBehaviour=}]
Session ID: eb78d1ac176166bdaa86da5dc12e09c0
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:326)
at org.openqa.selenium.remote.RemoteWebElement.clear(RemoteWebElement.java:139)
at com.selenium.com.selenium.practise.MultipleCasesUsingExcel.Test(MultipleCasesUsingExcel.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:571)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:707)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:979)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1116)
at org.testng.TestNG.runSuites(TestNG.java:1028)
at org.testng.TestNG.run(TestNG.java:996)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
Could any one Explain why I am getting this error and how it can be fixed
That's because you change page in your test, thus your element references break. Have a look at WebDriverExtensions. This framework provides method on opening your links in new windows without invalidating references of WebElements, and enables dynamic lookup of your elements.
Alternatively, if you don't want to use this framework, you could re-search for your elements in your loop like this:
//...
for (int j = 0; j < sheet.getColumns() - 1; j++) {
// add these lines
emailTextBox = driver.findElement(By.xpath("//input[#id='email']"));
pwdTextBox = driver.findElement(By.xpath("//input[#id='pass']"));
loginBtn = driver.findElement(By.xpath("//button[#id='send2']"));
// clear inputs before login. After you click loginBtn, the page
// changes, and references of WebElements are invalidated,
// thus your emailTextBox.clear(); methods threw anexception
emailTextBox.clear();
pwdTextBox.clear();
emailTextBox.sendKeys(sheet.getCell(j, i).getContents());
pwdTextBox.sendKeys(sheet.getCell(j + 1, i).getContents());
loginBtn.click();
}

Error: Permission denied to access property "navigator"

package automationFramework;
import java.awt.List;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.IllegalStateException;
public class Second_Practise {
public static void main(String[] args) throws InterruptedException {
String URL = "https://accounts.google.com/signin";
WebDriver driver;
System.setProperty("webdriver.gecko.driver", "D:\\geckodriver-v0.14.0-win64\\geckodriver.exe");
driver =new FirefoxDriver();
driver.get(URL);
WebElement Email = driver.findElement(By.id("identifierId"));
Email.sendKeys("dialogspp");
WebElement Next = driver.findElement(By.id("identifierNext"));
Next.click();
Thread.sleep(2000);
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//*[#id='password']/div[1]/div/div[1]/input")));
WebElement Password = driver.findElement(By.xpath(".//*[#id='password']/div[1]/div/div[1]/input"));
Password.sendKeys("dialogapp");
WebElement PassNext = driver.findElement(By.id("passwordNext"));
PassNext.click();
Thread.sleep(2000);
//WebElement gmail = driver.findElement(By.xpath("//a[#href='https://mail.google.com']"));
WebElement myDynamicElement2 = (new WebDriverWait(driver, 10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#href='https://mail.google.com']")));
myDynamicElement2.click();
Thread.sleep(2000);
WebElement myDynamicElement3 = (new WebDriverWait(driver, 10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#gh='cm']")));
myDynamicElement3.click();
}
}
I am using this piece of code to send an email, but on clicking "Compose" button i am getting the exception. i.e.
Jun 20, 2017 2:57:37 PM org.openqa.selenium.support.ui.ExpectedConditions findElement
WARNING: WebDriverException thrown by findElement(By.xpath: //div[#gh='cm'])
org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.xpath: //div[#gh='cm']
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: 'unknown', revision: '86a5d70', time: '2017-02-16 07:47:51 -0800'
System info: host: 'ANUM-PC', ip: '172.16.11.162', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
Driver info: driver.version: unknown
at org.openqa.selenium.support.ui.ExpectedConditions.lambda$findElement$0(ExpectedConditions.java:896)
at java.util.Optional.orElseThrow(Unknown Source)
at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:895)
at org.openqa.selenium.support.ui.ExpectedConditions.access$000(ExpectedConditions.java:41)
at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:205)
at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:201)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:234)
at automationFramework.Second_Practise.main(Second_Practise.java:35)
Exception in thread "main" org.openqa.selenium.JavascriptException: Error: Permission denied to access property "navigator"
Build info: version: 'unknown', revision: '86a5d70', time: '2017-02-16 07:47:51 -0800'
System info: host: 'ANUM-PC', ip: '172.16.11.162', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{rotatable=false, raisesAccessibilityExceptions=false, marionette=true, appBuildId=20161031133903, version=, platform=XP, proxy={}, command_id=1, specificationLevel=0, acceptSslCerts=false, browserVersion=47.0.2, platformVersion=6.1, XULappId={ec8030f7-c20a-464f-9b0e-13a3a9e97384}, browserName=Firefox, takesScreenshot=true, takesElementScreenshot=true, platformName=Windows_NT, device=desktop, firefox_profile=UEsDBBQACAgIACp31EoAAAAAAAAAA...}]
Session ID: b216dfb9-b672-4cd2-b7cc-087c74789afa
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:127)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:93)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:42)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:163)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:274)
at org.openqa.selenium.remote.RemoteWebElement.isDisplayed(RemoteWebElement.java:315)
at org.openqa.selenium.support.ui.ExpectedConditions.elementIfVisible(ExpectedConditions.java:302)
at org.openqa.selenium.support.ui.ExpectedConditions.access$100(ExpectedConditions.java:41)
at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:205)
at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:201)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:234)
at automationFramework.Second_Practise.main(Second_Practise.java:35)
I am able to access the element using firepath but error is still been there. Any suggestions?

Using Robot class to upload an image onto a website into a cropper tool. VK_ENTER not exiting file explorer

When looking at this post:
I got most of my solution but the VK_ENTER at the end did not take me back to the web page which leads to another issue of getting back into view of the page and not the cropper tool where the image is placed.
Can someone let me know what I need to do to get this to work?? Thanks!!
Here is the code:
public static void setClipboardData(String string) {
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
And that is what i do, just after opening the "open" window:
setClipboardData("C:\\path to file\\example.jpg");
//native key strokes for CTRL, V and ENTER keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Here is a link to a screen recording of how this is supposed to work(resizing and moving is not relevant to the issue)Upload profile picture]1
One of the issues is that the VK_ENTER is never done to leave file explorer and return to the web page. If I do it manually while the test is running the Save button is never found. Here is the error for that:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"/html/body/div[12]/form/div/div[1]/button[1]"}
Command duration or timeout: 30.10 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:59:12'
System info: host: 'Janet-PC', ip: '192.168.56.1', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=43.0.4, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: b7ceb493-af57-4290-a585-bc237e043848
*** Element info: {Using=xpath, value=/html/body/div[12]/form/div/div[1]/button[1]}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:353)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:490)
at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:345)
at groupPhotoUploadTest.groupPhotoUploadTest.main(groupPhotoUploadTest.java:54)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"/html/body/div[12]/form/div/div[1]/button[1]"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:59:12'
System info: host: 'Janet-PC', ip: '192.168.56.1', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_66'
Driver info: driver.version: unknown
at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/Janet/AppData/Local/Temp/anonymous8445833340663492444webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:10659)
at <anonymous class>.fxdriver.Timer.prototype.setTimeout/<.notify(file:///C:/Users/Janet/AppData/Local/Temp/anonymous8445833340663492444webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:621)
I have tried the Actions object as well as JavascriptExecutor and neither seem to work.
Here is the complete code:
package groupPhotoUploadTest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
public class groupPhotoUploadTest {
private static WebDriver driver;
private static String baseUrl;
public static void main(String[] args) throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://loadtest1.staging.brio.viddler.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl + "/");
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.name("email_address")).clear();
driver.findElement(By.name("email_address")).sendKeys("jfrank#viddler.com");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("Annie0308!");
driver.findElement(By.cssSelector("button.button")).click();
driver.findElement(By.linkText("Load Test1")).click();
driver.findElement(By.linkText("Manage Site")).click();
driver.findElement(By.linkText("Manage")).click();
driver.findElement(By.xpath("//div[#id='container']/div/table/tbody/tr[5]/td[6]/a")).click();
driver.findElement(By.linkText("Upload Logo")).click();
driver.findElement(By.name("image_file")).clear();
driver.findElement(By.name("image_file")).click();
// driver.findElement(By.name("image_file")).sendKeys("C:\\Users\\Janet\\Pictures\\P8291157.JPG");
setClipboardData("C:\\Users\\Janet\\Pictures\\P8291157.JPG");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
// robot.delay(5000);
/* WebElement saveLink = driver.findElement(By.xpath("/html/body/div[12]/form/div/div[1]/button[1]"));
Actions actions = new Actions(driver);
actions.moveToElement(saveLink);
actions.click();
actions.build().perform(); */
JavascriptExecutor jse = (JavascriptExecutor)driver;
WebElement saveLink = driver.findElement(By.xpath("/html/body/div[12]/form/div/div[1]/button[1]"));
jse.executeScript("arguments[0].click();", saveLink);
// driver.findElement(By.cssSelector("button.submit.button")).click();
}
public static void setClipboardData(String string) {
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
public void tearDown() throws Exception {
driver.quit();
}
}
Finally have it working. Here is the complete code. Had to use the cssSelector and not the xpath:
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(3000);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000);
Thread.sleep(5000);
WebElement saveLink = driver.findElement(By.cssSelector("button.submit.button"));
Actions actions = new Actions(driver);
actions.moveToElement(saveLink);
actions.click();
actions.build().perform();
Thread.sleep(5000);
WebElement submitLink = driver.findElement(By.cssSelector("input.button"));
actions.moveToElement(submitLink);
actions.click();
actions.build().perform();

I am trying to close the browser instance on Webdriver but unable to do so

package erewards2;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class login_sib2 {
public static void main(String[] args) {
FirefoxDriver d1 = new FirefoxDriver();
d1.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
d1.get("https://sib3.erewardsredeem.com/fm/customer.html?action=userLogin");
d1.manage().window().maximize();
WebElement e4 = d1.findElementByLinkText("Login");
e4.click();
d1.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement e1 = d1.findElement(By.id("showmemberid"));
e1.sendKeys("2800000091");
WebElement e2 = d1.findElementById("showmemberpwd");
e2.sendKeys("Miquser1");
WebElement e3 = d1.findElementByClassName("loginbtn");
e3.click();
WebElement e5 = d1.findElementByLinkText("Logout");
e5.click();
Alert a1 = d1.switchTo().alert(); //web based alert
WebDriverWait wait = new WebDriverWait(d1,10);
wait.until(ExpectedConditions.alertIsPresent()).accept();
a1.accept();
System.out.println("test1");
//close Firefox
d1.close();
System.out.println("test2");
// exit the program explicitly
System.exit(0);
System.out.println("test3");
}
}
I added the system.out println lines for test purpose and found that My code did not able to execute completely from Test1 statement. Below is the exception I got on my Eclipse IDE.
Exception in thread "main" org.openqa.selenium.NoAlertPresentException: No alert is present (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 13.82 seconds
Build info: version: '2.41.0', revision: '3192d8a', time: '2014-03-27 17:18:15'
System info: host: 'pcs-PC', ip: '192.168.1.64', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_25'
Session ID: 59fe366a-5fdc-4763-a6f2-0860bf1378be
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, browserConnectionEnabled=true, webStorageEnabled=true, nativeEvents=false, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=30.0}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:595)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:610)
at org.openqa.selenium.remote.RemoteWebDriver$RemoteAlert.accept(RemoteWebDriver.java:910)
at erewards2.login_sib2.main(login_sib2.java:40)
It looks like it fails before it gets to the close statement.
Try structuring your code like this:
FirefoxDriver d1 = new FirefoxDriver();
try {
// steps
}
finally {
d1.close();
}
This will guarantee the close statement is executed.
You can try using d1.quit() too.

Trying to get and print data from google search editbox but got InvalidElementStateException

I am trying to write a word in google search editbox and capture all the related list item and display it. But while doing so i got Got a exception
org.openqa.selenium.InvalidElementStateException: Element is disabled and so may not be used for actions. I went through the same exception related question and according to them changed my code but none of them help.
import java.util.List;
import java.util.concurrent.TimeUnit;
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.firefox.FirefoxProfile;
public class AutoIt {
public static void main(String[] args){
WebDriver window;
FirefoxProfile profile = new FirefoxProfile();
profile.setEnableNativeEvents(false);
window = new FirefoxDriver(profile);
try{
window.get("https://www.google.co.in/");
window.manage().window().maximize();
window.findElement(By.id("gs_htif0")).sendKeys("Shantanu Nandan");
window.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
List<WebElement> list=window.findElements(By.xpath("//td[#style='width: 100%;']/span"));
window.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
for(WebElement data:list){
System.out.println(data.getAttribute("value"));
}//for
}//try
catch(Exception e){
System.out.println("Got a exception");
e.printStackTrace();
window.close();
}//catch
finally{
System.out.println("Finally Block Executed ....");
window.close();
window.quit();
}//finally
}//main
}//class
Exception which i got for this code
org.openqa.selenium.InvalidElementStateException: Element is disabled and so may not be used for actions
Command duration or timeout: 47 milliseconds
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:12:12'
System info: host: 'omega-d52b83806', ip: '10.0.0.4', os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.7.0_45'
Session ID: d29ef567-95a8-47ce-bf84-c510cbb2756d
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, browserConnectionEnabled=true, webStorageEnabled=true, nativeEvents=false, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=29.0.1}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:89)
at AutoIt.main(AutoIt.java:21)
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Element is disabled and so may not be used for actions
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:12:12'
System info: host: 'omega-d52b83806', ip: '10.0.0.4', os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.7.0_45'
Driver info: driver.version: unknown
at <anonymous class>.fxdriver.preconditions.enabled(file:///C:/DOCUME~1/OMEGA/LOCALS~1/Temp/anonymous7567378475668954944webdriver-profile/extensions/fxdriver#googlecode.com/components/command_processor.js:8185)
at <anonymous class>.DelayedCommand.prototype.checkPreconditions_(file:///C:/DOCUME~1/OMEGA/LOCALS~1/Temp/anonymous7567378475668954944webdriver-profile/extensions/fxdriver#googlecode.com/components/command_processor.js:10814)
at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/DOCUME~1/OMEGA/LOCALS~1/Temp/anonymous7567378475668954944webdriver-profile/extensions/fxdriver#googlecode.com/components/command_processor.js:10831)
at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/DOCUME~1/OMEGA/LOCALS~1/Temp/anonymous7567378475668954944webdriver-profile/extensions/fxdriver#googlecode.com/components/command_processor.js:10836)
at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/DOCUME~1/OMEGA/LOCALS~1/Temp/anonymous7567378475668954944webdriver-profile/extensions/fxdriver#googlecode.com/components/command_processor.js:10778)
Finally Block Executed ....
You have selected the wrong element.
Use the below one for search text box
wb=window.findElement(By.name("q"));
Use the below for getting output suggestions.
List<WebElement> list = window.findElements(By.className("gsq_a"));
To get the values from the list, use getText() method instead of getAttribute().
for (WebElement data : list) {
System.out.println(data.getText());
}
Please try the below code
public class AutoSuggest {
WebDriver driver;
#Before
public void seup()
{
driver= new FirefoxDriver();
}
#Test
public void test_autosuggest()
{
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.google.co.in/");
driver.findElement(By.xpath("//div[#id='gs_lc0']//input[#id='gbqfq']")).sendKeys("h");
WebElement wb=driver.findElement(By.xpath("//td[#class='gssb_e']"));
List<WebElement> links= wb.findElements(By.tagName("div"));
System.out.println("the total "+links.size());
for (int i=0;i<links.size();i++)
{
System.out.println(links.get(i).getText());
}
}
}

Categories