I have a few selenium tests on a react application. All tests are passing for chrome and firefox without any error. However, in IE (internet explorer v11) - all tests pass, but fails at the tearDown method: -
teardown method: -
#AfterClass
public void tearDown(){
driver.close();
//driver.quit();
}
screenshot of TestNG error log: -
Browser Base Class: -
public class TestBase {
public static WebDriver driver;
public static Properties prop;
public static EventFiringWebDriver e_driver;
public static WebEventListener eventlistener;
public static ChromeDriver chrome;
public static WebDriver driverName;
public TestBase(){
try {
prop = new Properties();
FileInputStream ip = new FileInputStream("src/main/java/config/config.properties");
prop.load(ip);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e ){
e.printStackTrace();
}
}
public static void initialization(String browser){
try {
if(browser.equals("chrome")){
System.setProperty("webdriver.chrome.driver", "C:\\Browser\\chromedriver.exe");
driver = new ChromeDriver();
}else if (browser.equals("firefox")){
System.setProperty("webdriver.gecko.driver", "C:\\Browser\\geckodriver.exe");
driver = new FirefoxDriver();
}else if(browser.equals("ie")){
System.setProperty("webdriver.ie.driver", "C:\\Browser\\IEDriverServer.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability("nativeEvents", false);
ieCapabilities.setCapability("unexpectedAlertBehaviour", "accept");
ieCapabilities.setCapability("ignoreProtectedModeSettings", true);
ieCapabilities.setCapability("disable-popup-blocking", true);
ieCapabilities.setCapability("enablePersistentHover", true);
ieCapabilities.setCapability("ignoreZoomSetting", true);
driver = new InternetExplorerDriver(ieCapabilities);
}else if(browser.equals("edge")){
System.setProperty("webdriver.edge.driver", "C:\\Browser\\MicrosoftWebDriver.exe");
EdgeOptions options = new EdgeOptions();
options.setCapability("unexpectedAlertBehaviour", "accept");
driver = new EdgeDriver(options);
e_driver = new EventFiringWebDriver(driver);
//now create object of event listner handler to register it with eventfiring web driver
eventlistener = new WebEventListener();
e_driver.register(eventlistener);
driverName = driver;
driver = e_driver;
}
if(!browser.contains("edge")){
e_driver = new EventFiringWebDriver(driver);
//now create object of event listner handler to register it with eventfiring web driver
eventlistener = new WebEventListener();
e_driver.register(eventlistener);
driverName = driver;
driver = e_driver;
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
}
driver.get(prop.getProperty("url"));
} catch (TimeoutException e){
if (driver != null)
driver.close();
//driver.quit();
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
}
console error log
Starting MSEdgeDriver ... (...) on port 2440
Only local connections are allowed.
Please protect ports used by MSEdgeDriver and related test frameworks to prevent access by malicious code.
org.openqa.selenium.WebDriverException: unknown error: cannot find MSEdge binary
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T14:04:26.12Z'
System info: host: '<host>', ip: '<ip>', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_221'
Driver info: driver.version: EdgeDriver
remote stacktrace: Backtrace:
Ordinal0 [0x00007FF605E27542+1930562]
Ordinal0 [0x00007FF605D8BCC2+1293506]
Ordinal0 [0x00007FF605CF0801+657409]
Ordinal0 [0x00007FF605C60F1F+69407]
Ordinal0 [0x00007FF605C5EF02+61186]
Ordinal0 [0x00007FF605C87C9D+228509]
Ordinal0 [0x00007FF605C850EF+217327]
Ordinal0 [0x00007FF605C6702F+94255]
Ordinal0 [0x00007FF605C681EE+98798]
Ordinal0 [0x00007FF605DAA6A1+1418913]
GetHandleVerifier [0x00007FF605EE8AF9+656601]
GetHandleVerifier [0x00007FF605EE8891+655985]
GetHandleVerifier [0x00007FF605EF095C+688956]
GetHandleVerifier [0x00007FF605EE92D3+658611]
Ordinal0 [0x00007FF605DA069E+1377950]
Ordinal0 [0x00007FF605DACB46+1428294]
Ordinal0 [0x00007FF605DAB9BD+1423805]
BaseThreadInitThunk [0x00007FFF02907974+20]
RtlUserThreadStart [0x00007FFF0402A271+33]
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.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:123)
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Unknown Source)
at java.util.stream.ReferencePipeline.forEachWithCancel(Unknown Source)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.FindOps$FindOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.findFirst(Unknown Source)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:126)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:543)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:207)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
at org.openqa.selenium.edge.EdgeDriver.<init>(EdgeDriver.java:141)
at org.openqa.selenium.edge.EdgeDriver.<init>(EdgeDriver.java:130)
at com.testapp.base.TestBase.initialization(TestBase.java:73)
at com.testingapp.testcases.BusyIndicatorTest.setUp(BusyIndicatorTest.java:48)
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:108)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:523)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:224)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:146)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:166)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
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)
driver : InternetExplorerDriver: internet explorer on WINDOWS (d8509abb-d16b-4872-bdc2-010789af308c)
Trying to find Element By : By.xpath: //div[#id='hamburger_menu']
Exception occured: org.openqa.selenium.NoSuchSessionException: session d8509abb-d16b-4872-bdc2-010789af308c does not exist
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T14:04:26.12Z'
System info: host: '<host>', ip: '<ip>', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_221'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities {acceptInsecureCerts: false, browserName: internet explorer, browserVersion: 11, javascriptEnabled: true, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), se:ieOptions: {browserAttachTimeout: 0, elementScrollBehavior: 0, enablePersistentHover: true, ie.browserCommandLineSwitches: , ie.ensureCleanSession: false, ie.fileUploadDialogTimeout: 3000, ie.forceCreateProcessApi: false, ignoreProtectedModeSettings: true, ignoreZoomSetting: true, initialBrowserUrl: http://localhost:7136/, nativeEvents: true, requireWindowFocus: false}, setWindowRect: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: accept}
Session ID: <id>
What I've tried: -
initializing WebDriver driver = null in browser case class
Control Panel -> Internet Options -> Security -> Disabled "protected zone" for all four zones
ieCapabilities.setCapability("ignoreProtectedModeSettings", true); this is an alias for INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS
if(driver != null) {
driver.close();
}
I've tried all these which were mentioned in other stack overflow questions, however, I end up with the same error.
Do let me know if any more info. regarding the code is required.
EDIT:
I've noticed that my instance to the new InternetExplorerDriver has been striked through
driver = new InternetExplorerDriver (ieCapabilities);
This was striked, as DesiredCapabilities have been deprecated.
Before: -
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability("ignoreProtectedModeSettings", true);
driver = new InternetExplorerDriver(ieCapabilities);
Now: -
InternetExplorerOptions IEoptions = new InternetExplorerOptions();
IEoptions.setCapability("ignoreProtectedModeSettings", true);
driver = new InternetExplorerDriver(IEoptions);
This fixed the striked-through.
When I run the IE set of tests individually i.e. without chrome, firefox & edge tests. I can see all the tests passing & no error at teardown method. I am Unable to figure out the reason!
Related
I'm starting to automate a test for an Android mobile app with Appium which is a calculator application on my mobile.
To start, I want to test a simple additive "2 + 3 = 5" equation, I use Eclipse and Appium inspector to get the element Id.
This is my code :
public class CalculatorTest {
static AndroidDriver<AndroidElement> driver;
public static void main(String[] args)
{
try {
openCalculator();
} catch (Exception e) {
System.out.println(e.getCause());
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void openCalculator() throws MalformedURLException, InterruptedException {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("deviceName", "OPPO A73");
cap.setCapability("udid", "9b487dea");
cap.setCapability("platformName", "Android");
cap.setCapability("platformVersion", "11");
cap.setCapability("appPackage", "com.coloros.calculator");
cap.setCapability("appActivity", "com.android.calculator2.Calculator");
URL url = new URL("http://127.0.0.1:4723/wd/hub");
driver = new AndroidDriver<AndroidElement>(url, cap);
System.out.println("Application started ..... ");
MobileElement agree= driver.findElement(By.id("com.coloros.calculator:id/btn_confirm"));
agree.click();
System.out.println("Application started ..... ");
driver.manage().timeouts().implicitlyWait(25,TimeUnit.SECONDS);
MobileElement one= driver.findElement(By.id("com.coloros.calculator:id/digit_2"));
MobileElement add= driver.findElement(By.id("com.coloros.calculator:id/op_add"));
MobileElement two= driver.findElement(By.id("com.coloros.calculator:id/digit_3"));
MobileElement equal= driver.findElement(By.id("com.coloros.calculator:id/eq"));
one.click();
add.click();
two.click();
equal.click();
}
}
The calculator app start with , If I click on agree I go to the .
In my code, I just click on agree button And then I want to click on 2 plus 1 and equal, But I got this an error as follows :
org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters.
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-IJHSE2I', ip: '192.168.1.146', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '16.0.2'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities {appActivity: com.android.calculator2.Cal..., appPackage: com.coloros.calculator, databaseEnabled: false, desired: {appActivity: com.android.calculator2.Cal..., appPackage: com.coloros.calculator, deviceName: OPPO A73, platformName: android, platformVersion: 11, udid: 9b487dea}, deviceApiLevel: 30, deviceManufacturer: OPPO, deviceModel: CPH2095, deviceName: 9b487dea, deviceScreenDensity: 480, deviceScreenSize: 1080x2400, deviceUDID: 9b487dea, javascriptEnabled: true, locationContextEnabled: false, networkConnectionEnabled: true, pixelRatio: 3, platform: LINUX, platformName: Android, platformVersion: 11, statBarHeight: 96, takesScreenshot: true, udid: 9b487dea, viewportRect: {height: 2076, left: 0, top: 96, width: 1080}, warnings: {}, webStorageEnabled: false}
Session ID: 3a2d4b25-9e4a-4aa8-a9cf-6b0faa812c6a
*** Element info: {Using=id, value=com.coloros.calculator:id/digit_2}
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:62)
at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:372)
at io.appium.java_client.DefaultGenericMobileDriver.findElementById(DefaultGenericMobileDriver.java:70)
at io.appium.java_client.AppiumDriver.findElementById(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElementById(AndroidDriver.java:1)
at org.openqa.selenium.By$ById.findElement(By.java:188)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:58)
at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
at appiumtests.CalculatorTest.openCalculator(CalculatorTest.java:52)
at appiumtests.CalculatorTest.main(CalculatorTest.java:25)
I found a solution in the following link
solution but I want to do it automatically with Java in my code.
How to locate an element in android app in new screen with Appium
I'm encountering the below error while trying to set Request headers using browsermobproxy for selenium tests.
Exception in thread "main" org.openqa.selenium.WebDriverException: : Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:24:21.231Z'
System info: host: 'G9HQBVT2E', ip: '10.62.6.122', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_271'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 87.0.4280.141, chrome: {chromedriverVersion: 87.0.4280.20 (c99e81631faa0..., userDataDir: C:\Users\abc\AppData\...}, goog:chromeOptions: {debuggerAddress: localhost:64062}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(manual, http=G9HQBVT2..., setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:virtualAuthenticators: true}
Session ID: 73d6ecf19b420b0bc368f2bc3d5f78b1
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:423)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:485)
at com.sample.test.DataReader.main(DataReader.java:79)
Driver program
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Try\\drivers\\chromedriver.exe"); //PropertyReader.getProperty("chromedriverpath")
// start the proxy
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
proxy.start(0);
// get the Selenium proxy object
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
String chromeProfilePath = "C:\\Users\\AppData\\Local\\Google\\Chrome\\User Data\\Default";
//capabilities
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-web-security");
options.addArguments("--ignore-certificate-errors");
options.addArguments("--user-data-dir="+chromeProfilePath);
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
//capabilities.setCapability("disable-web-security", true);
// start the browser up
WebDriver driver = new ChromeDriver(capabilities);
// enable more detailed HAR capture, if desired (see CaptureType for the complete list)
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
//
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");
String jsScript = "localStorage.setItem('profiles', JSON.stringify([{ title: 'Selenium', hideComment: true, appendMode: '', \n" +
" headers: [ \n" +
" {enabled: true, name: 'token-1', value: '{\"abc\": 1234, \"type\": \"def\"}', comment: ''}\n" +
" ], \n" +
" respHeaders: [],\n" +
" filters: []\n" +
" }]));";
((JavascriptExecutor)driver).executeScript(jsScript);
// create a new HAR with the label "yahoo.com"
proxy.newHar("localhost:4200");
// open app
driver.get("http://localhost:4200/app/");
It would be great if anyone can help me on this. Thank you.
This is because your browser privacy settings disallow javascript on the page to set up cookies (third-party cookies). You need to change them using properties.
The list of relevant properties you can find here: https://stackoverflow.com/a/48670137/8343843
How to set the property with web driver you can find here: https://stackoverflow.com/a/25090103/8343843
On doing a driver.close();driver.quit(); during the execution of java code, the following error is thrown:
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Tried to run command without establishing a connection
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'ADMIN-PC', ip: '192.168.1.6', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{moz:profile=C:\Users\admin\AppData\Local\Temp\rust_mozprofile.ENTBvl2aDbSs, rotatable=false, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, moz:headless=false, platform=XP, specificationLevel=0, moz:accessibilityChecks=false, acceptInsecureCerts=true, browserVersion=56.0.2, platformVersion=10.0, moz:processID=5004, browserName=firefox, javascriptEnabled=true, platformName=XP}]
Session ID: 82e7dabd-c178-4d90-a3f8-84dc3f6ff14f
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:185)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:120)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:643)
at org.openqa.selenium.remote.RemoteWebDriver.quit(RemoteWebDriver.java:482)
at yahoo.main(yahoo.java:34)
Sharing code that throws the above exception :
//package basicSeleniumScripts;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class yahoo {
public static void main(String[] args) {
String Firefoxdriverpath = "C:\\Marionette\\geckodriver_1.exe";
WebDriver driver;
System.setProperty("webdriver.gecko.driver",Firefoxdriverpath);
//create a new instance of Firefox driver
driver = new FirefoxDriver();
//Open the page we want to open
driver.get("http://www.yahoo.com");
//Defining expected title
String expectedTitle = "Yahoo";
//Getting the actual title
String actualTitle = null;
actualTitle = driver.getTitle();
//Validating the TestCase
if (actualTitle.contentEquals(expectedTitle))
{
System.out.println("Test Passed");
}
else
{
System.out.println("Test Failed!!!");
}
driver.close();
driver.quit();
}
}
Update the gecko driver version to v0.19.0 as you are using 3.6.0 jars of selenium.
Also use quit method only
Error Message in console is as below.
Getting below error when trying to click on the button in child window.
org.openqa.selenium.NoSuchElementException: no such element
(Session info: chrome=40.0.2214.111)
(Driver info: chromedriver=2.9.248315,
platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 30.05 seconds
For documentation on this error,
please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.44.0',
revision: '76d78cf',
time: '2014-10-23 20:03:00'
System info: host: 'AS-Ramesh',
ip: '*******',
os.name: 'Windows 7',
os.arch: 'x86',
os.version: '6.1',
java.version: '1.7.0_17'
Session ID: 0e85209c610382395e8dee65a9766bd2
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP,
acceptSslCerts=true,
javascriptEnabled=true,
browserName=chrome,
chrome={userDataDir=C:\Users\rameshp\AppData\Local\Temp\scoped_dir27484_24934},
rotatable=false,
locationContextEnabled=true,
version=40.0.2214.111,
takesHeapSnapshot=true,
cssSelectorsEnabled=true,
databaseEnabled=false,
handlesAlerts=true,
browserConnectionEnabled=false,
webStorageEnabled=true,
nativeEvents=true,
applicationCacheEnabled=false,
takesScreenshot=true}]
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: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.findElement(RemoteWebDriver.java:352)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:449)
at org.openqa.selenium.By$ByXPath.findElement(By.java:357)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at FEPModule.FEPLogin.Login_Main(FEPLogin.java:176)
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:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
The code is as below
public class FELogin {
private WebDriver driver;
private String url, myuserName, myPassword, LoginUsernamelink, LoginPasswordlink, LoginOklink, OpenFEModulelink;
#BeforeTest
public void setUp() throws Exception {
//get values from OR.Properties file
FileInputStream conf=new FileInputStream("C:\\eclipse new selenium\\Proj\\Config\\OR.Properties");
Properties p=new Properties();
p.load(conf);
Thread.sleep(1000);
url=p.getProperty("testSiteName");
Thread.sleep(1000);
myuserName=p.getProperty("myusername_link");
myPassword=p.getProperty("mypassword_link");
LoginUsernamelink=p.getProperty("LoginUsername_link");
LoginPasswordlink=p.getProperty("LoginPassword_link");
LoginOklink=p.getProperty("LoginOk_link");
OpenFEModulelink=p.getProperty("OpenFEModule_link");
//Chrome Driver Configuration
System.setProperty("webdriver.chrome.driver", "C:\\Selenium JARs\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
driver = new ChromeDriver(options);
driver.get(url);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//maximize chrome window
driver.manage().window().maximize();
Thread.sleep(1000);
}
#Test
public void Login_Main() throws InterruptedException {
//Enter username
driver.findElement(ById.xpath(LoginUsernamelink)).clear();
driver.findElement(ById.xpath(LoginUsernamelink)).sendKeys("user");
Thread.sleep(1000);
//Enter password
driver.findElement(ById.xpath(LoginPasswordlink)).clear();
driver.findElement(ById.xpath(LoginPasswordlink)).sendKeys("New#123");
Thread.sleep(1000);
//login to website
driver.findElement(ById.xpath(LoginOklink)).click();
Thread.sleep(6000);
driver.switchTo().frame(0);
Thread.sleep(1000);
driver.findElement(ById.cssSelector(OpenFEModulelink)).click();
Thread.sleep(3000);
String ParentWindow = driver.getWindowHandle();
Thread.sleep(200);
for(String childHandle: driver.getWindowHandles()){
Thread.sleep(100);
driver.switchTo().window(childHandle);
Thread.sleep(100);
}
//the below code for login to child window
Thread.sleep(1000);
//enter user name
driver.findElement(By.id("username")).sendKeys("user");
Thread.sleep(1000);
//enter password
driver.findElement(By.id("password")).sendKeys("New#123");
Thread.sleep(1000);
//login to website
driver.findElement(By.name("submit")).click();
Thread.sleep(3000);
driver.manage().window().maximize();
Thread.sleep(5000);
//------upto here working fine-------------
//click on search button in child window
//----The below code is not working for me---getting exception(no such element)
driver.findElement(ById.xpath(".//*[#id='zT7Tg3']")).click();
Thread.sleep(1000);
}
HTML source might help me better to analyze. However, you can also debug the code by using getpagesource() function after switching to particular frame or window to check if it's properly switching to the page and see if the element is available in the page you are switching to.
I am trying to access a webtable which is quite static and get the values from each row.
I am getting an error, the code is:
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class TS1_TC2 {
WebDriver driver=null;
String btn1="html/body/form/div[1]/center/table/tbody/tr/td[1]/input";
String table="html/body/form/table/tbody/tr[2]/td/div/center/table";
#BeforeTest
public void browserCheck()
{
driver=new FirefoxDriver();
driver.get("http://demo.borland.com/gmopost/");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
#Test
public void TS1_TC2()
{
driver.findElement(By.xpath(btn1)).click();
//html/body/form/table/tbody/tr[2]/td/div/center/table/tbody
//html/body/form/table/tbody/tr[2]/td/div/center/table
WebElement table=driver.findElement(By.xpath("html/body/form/table/tbody/tr[2]/td/div/center/table"));
List<WebElement> rows=table.findElements(By.tagName("tr"));
//WebDriverWait wait = new WebDriverWait(driver, 100, 15);
System.out.println(rows.size());
for(int rownum=2;rownum<rows.size();rownum++)
{
List<WebElement> cols=rows.get(rownum).findElements(By.tagName("td"));
System.out.println(cols.size());
for(int colnum=1;colnum<cols.size();colnum++)
{
//System.out.println(cols.get(colnum).getText());
//wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("html/body/form/table/tbody/tr[2]/td/div/center/table/tbody/tr["+rownum+"]/td["+colnum+"]")));
System.out.println("html/body/form/table/tbody/tr[2]/td/div/center/table/tbody/tr["+rownum+"]/td["+colnum+"]");
System.out.println(cols.get(colnum).findElement(By.xpath("html/body/form/table/tbody/tr[2]/td/div/center/table/tbody/tr["+rownum+"]/td["+colnum+"]")).getText());
System.out.println("--");
}
System.out.println();
}
}
}
The Exception thrown is as follows:
FAILED: TS1_TC2
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"html/body/form/table/tbody/tr[2]/td/div/center/table/tbody/tr[2]/td[1]"}
Command duration or timeout: 20.08 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.40.0', revision: 'fbe29a9', time: '2014-02-19 20:55:11'
System info: host: 'Vihaan-PC', ip: '192.168.1.3', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_51'
Session ID: 15f51aea-04cd-4ea4-bdae-0bdd47312bd7
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:573)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
at org.openqa.selenium.remote.RemoteWebElement.findElement(RemoteWebElement.java:171)
at org.openqa.selenium.remote.RemoteWebElement.findElementByXPath(RemoteWebElement.java:244)
at org.openqa.selenium.By$ByXPath.findElement(By.java:357)
at org.openqa.selenium.remote.RemoteWebElement.findElement(RemoteWebElement.java:167)
at TS1_TC2.TS1_TC2(TS1_TC2.java:57)
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:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Unable to locate element: {"method":"xpath","selector":"html/body/form/table/tbody/tr[2]/td/div/center/table/tbody/tr[2]/td[1]"}
Build info: version: '2.40.0', revision: 'fbe29a9', time: '2014-02-19 20:55:11'
System info: host: 'Vihaan-PC', ip: '192.168.1.3', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_51'
Driver info: driver.version: unknown
at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/Vihaan/AppData/Local/Temp/anonymous7820392430389922124webdriver-profile/extensions/fxdriver#googlecode.com/components/driver_component.js:8904)
at <anonymous class>.fxdriver.Timer.prototype.setTimeout/<.notify(file:///C:/Users/Vihaan/AppData/Local/Temp/anonymous7820392430389922124webdriver-profile/extensions/fxdriver#googlecode.com/components/driver_component.js:396)
Kindly help , because I see the the xpath from firepath is exactly the same as the xpath fetched in the for loop.
Thanks
rajee
try using
driver.findElement(By.xpath("html/body/form/table/tbody/tr[2]/td/div/center/table/tbody/tr["+rownum+"]/td["+colnum+"]")).getText()
instead of
cols.get(colnum).findElement(By.xpath("html/body/form/table/tbody/tr[2]/td/div/center/table/tbody/tr["+rownum+"]/td["+colnum+"]")).getText()
It should work.
But I dont understand why you used the above line. The following code achieves the same thing.
WebDriver driver = null;
#BeforeTest
public void browserCheck() {
driver = new FirefoxDriver();
driver.get("http://demo.borland.com/gmopost/");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
#Test
public void TS1_TC2() {
driver.findElement(By.name("bSubmit")).click();
WebElement table = driver
.findElement(By
.xpath("//form[#name='Items']/table/tbody/tr[2]/td/div/center/table"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
for (int rownum = 2; rownum < rows.size(); rownum++) {
List<WebElement> cols = rows.get(rownum).findElements(
By.tagName("td"));
for (int colnum = 1; colnum < cols.size(); colnum++) {
System.out.println(cols.get(colnum).getText());
}
System.out.println("\n");
}
}
Let me know if this helps you.