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.
Related
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!
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
I have written a selenium test for yahoo website. In this test I am testing Yahoo News. But this code is throwing an Exception. So please solve the problem?
I am using Eclipse IDE, and Firefox as browser.
Code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Tests {
WebDriver driver;
Wait<WebDriver> wait;
boolean result;
Tests() {
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 30);
driver.get("http://www.yahoo.com/");
}
public static void main(String arg[]) {
new Tests().news();
}
public boolean news() {
try {
System.out.print("Testing News... ");
driver.findElement(By.linkText("https://www.yahoo.com/news/")).click();
driver.findElement(By.partialLinkText("/news/world/")).click();
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver webDriver) {
return webDriver.findElement(By.id("th-title")) != null;
}
});
return driver.findElement(By.id("th-title")).getText().contains("World");
}
catch(Exception exp) {
exp.printStackTrace();
return false;
}
}
}
Exception:
Testing News... org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"https://www.yahoo.com/news/"}
Command duration or timeout: 21.55 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40'
System info: host: 'Jahanzeb', ip: '10.99.14.207', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.7.0_79'
*** Element info: {Using=link text, value=https://www.yahoo.com/news/}
Session ID: 7576b452-dcb2-448f-844c-6c8b499561f1
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=WINDOWS, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, nativeEvents=false, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=46.0.1}]
FAILED
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:678)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByLinkText(RemoteWebDriver.java:428)
at org.openqa.selenium.By$ByLinkText.findElement(By.java:246)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
at Tests.news(Tests.java:72)
at Main.main(Main.java:14)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"https://www.yahoo.com/news/"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40'
System info: host: 'Jahanzeb', ip: '10.99.14.207', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.7.0_79'
Driver info: driver.version: unknown
at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous2826618494991255784webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:10770)
at <anonymous class>.FirefoxDriver.prototype.findElement(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous2826618494991255784webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:10779)
at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous2826618494991255784webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12661)
at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous2826618494991255784webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12666)
at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous2826618494991255784webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12608)
Please examine Yahoo page.
Please press Ctrl-F and try to find a text: "https://www.yahoo.com/news/">
There is no such a text there.
But if you look into a html source of this page, you will find this A tag with href attriibutte = ""https://www.yahoo.com/news/":
<a class="C(#fff) Td(n) Td(u):h" href="https://www.yahoo.com/news/"
data-reactid=".pgwo63s1xy.$tgtm-UH-0-Header.1.0.0:$news.0">News</a>
But a "link text" of this link is not "https://www.yahoo.com/news/", but "News" . The By#linkText method is looking for the link text (in this case "News"), not for href attributte.
You need to replace this command:
driver.findElement(By.linkText("https://www.yahoo.com/news/")).click();
with this one:
driver.findElement(By.linkText("News")).click();
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 have created this test script to test a website. The problem is that sometime i am able to click edit button but sometime i am getting NoElementFoundException for the same button. I searched for the same type of problem on the forum and did the code changes as per recommended but non of them worked for me. In the attached picture i circled the button in red colour for which i am getting the exception.
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;
public class MonsterUpdateNewProfile {
static WebDriver window=new FirefoxDriver();
static WebElement wb;
static String[] data;
#Test(priority=2)
static public boolean isAlertExist(){
boolean alert=false;
try{
Alert alt= window.switchTo().alert();
alert=true;
System.out.println("Text from alert is "+alt.getText());
alt.dismiss();
}catch(Exception e){
System.out.println("No Alert");
e.printStackTrace();
}
return alert;
}
#Test
static void dropdown() throws InterruptedException {
wb=window.findElement(By.xpath("//div[#class='ns_menu_item_wrap ns_lt active']/a"));
Actions mouse=new Actions(window);
mouse.moveToElement(wb).perform();
Thread.sleep(4000);
Select select=new Select(wb);
select.selectByIndex(1);
}//dropdown
#Test
public static void monster() throws InterruptedException {
try{
//connecting to web site by sending address url
window.get("https://my.monsterindia.com/login.html?src=http://my.monsterindia.com/my_monster.html&rand=5257");
window.manage().window().maximize();
window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
//finding username by using xpath
wb=window.findElement(By.id("BodyContent:txtUsername"));
//sending username
wb.sendKeys("sshantanunandan#gmail.com");
//finding and sending password
window.findElement(By.id("BodyContent_txtPassword")).sendKeys("Ferrari2738");
window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
//finding and clicking on login button
window.findElement(By.name("submit")).click();
//grtting the title of current page using getTitle() method
System.out.println(window.getTitle());
window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
window.findElement(By.name("cancel")).click();
window.findElement(By.className("flyout_close")).click();
//locating and clicking on update button which will open a new window
window.findElement(By.xpath("//img[#src='http://media.monsterindia.com/monster_2012/btn_update2.gif']")).click();
window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
//capturing the title of oldwindow or the window which we go after loging
//using getWindowHandle() method
String oldwindow=window.getWindowHandle();
//by using for statement getting the title of new pop upwindow
//here we can use if or while statement as well using getWindowHandles() method
for(String newwindow : window.getWindowHandles()){
//swithching to the new pop up using window.switchTo().window(passing newwindow as argument)
window.switchTo().window(newwindow);}
//getting title of new window using getTitle() method
System.out.println("NewWindow Title"+ window.getTitle());
window.findElement(By.xpath(".//*[#id='edit_resume_section3_open' and not(#disabled)]")).click();
window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
System.out.println(window.findElement(By.xpath("//input[#name='title']")).getAttribute("value"));
window.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
window.findElement(By.id("update")).click();
window.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
window.close();
//switching to oldwindow or main window
//using switchTo().window(passing oldwindow url to it)
//url which we captured in String oldwindow=window.getWindowHandle() method
window.switchTo().window(oldwindow);
//getting the output of old window
System.out.println("OldWindow Title" + window.getTitle());
//isAlertExist();
//dropdown();
}//try
catch(NoSuchElementException e){
window.findElement(By.className("flyout_close")).click();
window.findElement(By.xpath("//a[#href='http://my.monsterindia.com/view_resume.html?resid=51706134&mode=edit']/img")).click();
window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
window.findElement(By.id("edit_resume_section3_open")).click();
window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
System.out.println(window.findElement(By.xpath("//input[#name='title']")).getAttribute("value"));
window.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
window.findElement(By.id("edit_resume_section3_close_other")).click();
window.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//isAlertExist();
dropdown();
}//catch
catch(Exception e){
e.printStackTrace();
System.out.println("Got Acception");
window.close();
}//catch
finally{
//dropdown();
System.out.println("Finally Closing");
window.close();
window.quit();
}//finally
}//main
}//class
Exception got for this code-
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//input[#name='title']"}
Command duration or timeout: 40.06 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:12:12'
System info: host: 'omega-d52b83806', ip: '10.0.0.5', os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.7.0_45'
Session ID: f4dce968-0425-4ba1-8a62-4ebdff91edc8
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.RemoteWebDriver.findElement(RemoteWebDriver.java:307)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:404)
at org.openqa.selenium.By$ByXPath.findElement(By.java:363)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:299)
at MonsterUpdateNewProfile.monster(MonsterUpdateNewProfile.java:74)
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":"//input[#name='title']"}
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:12:12'
System info: host: 'omega-d52b83806', ip: '10.0.0.5', 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>.FirefoxDriver.prototype.findElementInternal_(file:///C:/DOCUME~1/OMEGA/LOCALS~1/Temp/anonymous591356915052066864webdriver-profile/extensions/fxdriver#googlecode.com/components/driver_component.js:8860)
at <anonymous class>.fxdriver.Timer.prototype.setTimeout/<.notify(file:///C:/DOCUME~1/OMEGA/LOCALS~1/Temp/anonymous591356915052066864webdriver-profile/extensions/fxdriver#googlecode.com/components/driver_component.js:396)
Posting an answer as I couldn't work out how to place code in comments...
The error says it can't find the element, so either the XPath has an issue, or the element doesn't exist. You could try making the element your wait condition.
....
WebDriverWait wait = new WebDriverWait(webDriver, 30)
window.findElement(By.id("...")).click();
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#name='title']")))
webDriver.findElement(By.xpath("//input[#name='title']"))
....
Please check your XPath ".//*[#id='edit_resume_section3_open' and not(#disabled)]" correctness.
If it is correct then try to wait for this element and if it is available then only click on it.
You can use below code to wait for element:
(new WebDriverWait(driver, 60)).until(new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver d) {
return d.findElement(By.xpath(".//*[#id='edit_resume_section3_open' and not(#disabled)]"));
}
});