Java try-catch not catching exception - java

I have the following method:
private void checkIfLoggedIn() {
try{
try {
new WebDriverWait(driver, 10)
.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector("a[href*='score']")));
}
catch (WebDriverException e) {
}
loggedInState = 2;
}
catch (TimeoutException e) {
loggedInState = -1;
}
}
Simply put, this method's job is to wait until the webpage finishes loading the logged-in pa
ge, and let the rest of the code know by changing a variable. This code works perfectly the vast majority of the time, however if the driver is closed (by another thread) before it finishes, it crashes. I'm perfectly fine with the code stopping - If the webpage has closed it has most likely finished it's task (or crashed for a different reason). The problem is that the error log (posted below) won't go away. I'v even tried something as broad as catch (Exception e)in order to catch any possible exception, but the crashlog won't go away. Any Advice would be appreciated!
EDIT: Thanks to #jdigital, I discovered that the code was in fact catching the exceptions, however that was masked by Selenium outputting it's own exceptions. Any advice on how to have selenium stop outputting errors would be appreciated!
Jan 27, 2014 6:48:29 PM org.openqa.selenium.support.ui.ExpectedConditions findElement
WARNING: WebDriverException thrown by findElement(By.selector: a[href*='score'])
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:11:15'
System info: host: '[Edited out for Privacy]', ip: '[Edited out for Privacy]', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_45'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:307)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:396)
at org.openqa.selenium.By$ByCssSelector.findElement(By.java:432)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:299)
at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:730)
at org.openqa.selenium.support.ui.ExpectedConditions.access$0(ExpectedConditions.java:728)
at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:130)
at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:1)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:208)
at Web.WebCrawler.checkIfLoggedIn(WebCrawler.java:89)
at Web.WebCrawler.access$0(WebCrawler.java:86)
at Web.WebCrawler$1.run(WebCrawler.java:80)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:117)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:178)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:144)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:131)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:610)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:445)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at org.openqa.selenium.remote.HttpCommandExecutor.fallBackExecute(HttpCommandExecutor.java:319)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:298)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.execute(NewProfileExtensionConnection.java:165)
at org.openqa.selenium.firefox.FirefoxDriver$LazyCommandExecutor.execute(FirefoxDriver.java:366)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:527)
... 13 more

You should be able to set Selenium's Logging Preferences to customize the exception output.
EDIT:
Perhaps the instructions at the above referenced link aren't too helpful.
It looks like Selenium uses the standard Java logger interface. Get hold of the RemoteWebDriver object and then turn off its logging via setLogLevel(java.util.logging.Level.OFF).
For another alternative, the FirefoxDriver allows stdout/stderr to be redirected to a file. This has the advantage of allowing you to inspect the output should you need to do so; otherwise, you can just overwrite it or delete it.

Related

Selenium not waiting for page to load

I'm doing some tests with Selenium, and the tests have to login to a system. This login takes 17 seconds to fully happen.
The system has to wait for it to finish, otherwise the whole test fails.
I've tried many ways to do that, but all of them fail.
First code I've tried was this:
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
When I use that, even though I tell it to wait for 100 seconds (which is almost 2 full minutes!), I get a timeout 2 seconds later with this stacktrace.
org.openqa.selenium.WebDriverException: timeouts
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'CMTCLX62137', ip: '53.19.227.206', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_31'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{moz:profile=C:\Users\ALEX\AppData\Local\Temp\rust_mozprofile.Z2KJE568nWB8, rotatable=false, timeouts={implicit=0.0, pageLoad=300000.0, script=30000.0}, pageLoadStrategy=normal, moz:headless=false, platform=ANY, proxy=Proxy(manual, http=localhost), specificationLevel=0.0, moz:accessibilityChecks=false, acceptInsecureCerts=true, browserVersion=56.0, platformVersion=6.1, moz:processID=21116.0, browserName=firefox, javascriptEnabled=true, platformName=windows_nt}]
Session ID: b2dca4a5-623a-4311-ad07-6444785dbcaf
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:150)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:115)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:45)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
at org.openqa.selenium.remote.RemoteWebDriver$RemoteWebDriverOptions$RemoteTimeouts.implicitlyWait(RemoteWebDriver.java:868)
Another code I've tried:
new WebDriverWait(driver, 100).until(webDriver -> ((JavascriptExecutor) webDriver).executeScript(
"return document.readyState").equals("complete"));
Using this, it just doesn't wait and I get a
org.openqa.selenium.NoSuchElementException: Unable to locate element
The only way for my test to work is using a Thread.sleep(), but this is a really bad option, because sometimes it loads faster than expected and sometimes it still fails because it takes more than 17s.
Any other option to wait for the page to fully load?
This is already solved here: Selenium wait until document is ready
Anyways I usually wait for controls I need to use, instead of waiting until full page is loaded:
wait.until(ExpectedConditions.elementToBeClickable(By
.id(ConfigData.IDs.buttonLogin)));
I guess used elementToBeClickable() with Explicit wait instead of Page Load
WebElement ele= driver.findElement("Locator Value");
WebDriverWait wait=new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(ele));
ele.click();

Change Password Test Cases Selenium - Debug

Below is the test that i wrote for changing password.
#Test
public void changePassword() throws IOException, InterruptedException {
Login();
driver.findElement(By.xpath(".//*[#id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/a")).click();
driver.findElement(By.xpath(".//*[#id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/ul/li[3]/a")).click();
driver.findElement(By.xpath(".//*[#id='change-password']/div[1]/div/input")).sendKeys("abcd");
driver.findElement(By.xpath(".//*[#id='Users_password']")).sendKeys("xyz123456");
driver.findElement(By.xpath(".//*[#id='repassword']")).sendKeys("xyz123456");
driver.findElement(By.xpath(".//*[#id='change-password']/div[4]/div/input")).click();
}
}
Below is the Error that I am getting, I have checked the Xpath is correct, Still getting this error -
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[#id='change-password']/div[1]/div/input"}
Command duration or timeout: 2.81 seconds
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.ErrorHandler.createThrowable(ErrorHandler.java:215)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:671)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:410)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:509)
at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:402)
at pages.ChangePass.changePassword(ChangePass.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
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:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[#id='change-password']/div[1]/div/input"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'DESKTOP-1AKPPH7', ip: '192.168.56.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_111'
Driver info: driver.version: unknown
at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:11390)
at <anonymous class>.FirefoxDriver.prototype.findElement(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:11399)
at <anonymous class>.DelayedCommand.prototype.executeInternal_/k(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12879)
at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12884)
at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12826)
My questions are -
1. What is wrong in above code, When i execute this it takes me to the change password screen.
2. Is above way the best way to test change password functionality?
3. Are there any more test scenarios that you can recomend me to include and how?
First try to add HTML snippet , so the locators can be written in much more redundant way.
2nd , Use some wait mechanism for the page to be loaded properly. In your case You are clicking on a link and trying to enter data in change password input filed, the exception you are getting due to the reason the page is not loaded properly and Selenium trying to enter the value in change password filed.
For a simple solution you can use Implicit wait and it will work
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Here are the Answers to your Question:
What is wrong in above code:
The xpaths you have constructed, e.g. .//*[#id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/a, .//*[#id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/ul/li[3]/a and .//*[#id='change-password']/div[1]/div/input are absolute xpaths which contains index. Hence they are brittle and vulnerable. You can consider constructing unique logical xpath.
Is above way the best way to test change password functionality?:
I don't think there are best practices in this. Because it is really depended on what you are trying to solve. But definitely before using sendKeys("abcd") method for a text field, you should consider using clear() method first.
When there is a NoSuchElementException: Unable to locate element, we should consider inducing ExplicitWait with proper ExpectedConditions so Selenium can locate the element atleast.
Let me know if this Answers your Question.

InvalidSelectorException thrown despite the Xpath being syntactically correct

In my webdriver script, I'm trying to get a webElement[which happens to be a page heading] & fetching the locators & locations through the .properties file.
First & foremost query is that if your xpath is syntactically correct, do you get such an exception[Exception given below]?. I'm confused at this point because of the message appended along with the exception which is cannot be evaluated or does notresult in a WebElement
Setup Details,
OS => Windows 7
Browser => IE 9
Webdriver version => 2.44.0.0
IE driver server => 32 bit
Following is the xpath[copied from the properties file],
.//*[#id='frmPDAuditReports']//table[#class='PageHeading']/tbody/tr/td
Code for getting the webElement is,
public WebElement pageHeading() throws Exception
{
boolean elementFoundMessage = CreatePolicyApprovalDeviationRequestPageObjectRetriever.customElementWaitWithTimeoutWithProperties(driver,CreatePolicyApprovalDeviationRequestPageObjectRetriever.getLocator("pageHeading", "Page Heading"),elementTimeout);
if(elementFoundMessage)
{
element = CreatePolicyApprovalDeviationRequestPageObjectRetriever.returnWebElement(driver, CreatePolicyApprovalDeviationRequestPageObjectRetriever.getLocator("pageHeading", "Page Heading"));
}
else
{
log.error("PageHeading():Element not found: Null Returned");
}
return element;
}
Concerned part of the properties file looks like,
pageHeading = xpath : .//*[#id='frmPDAuditReports']//table[#class='PageHeading']/tbody/tr/td
Now, the xpath is syntactically correct & i have verified it through the firepath.For that fact the xpath actually worked fine during most of my executions.Just once the exception was thrown, which is given below,
org.openqa.selenium.InvalidSelectorException: The xpath expression './/*[#id='frmPDAuditReports']//table[#class='PageHeading']/tbody/tr/td' cannot be evaluated or does notresult in a WebElement (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 47 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '2.46.0', revision: '87c69e2', time: '2015-06-04 16:17:10'
System info: host: 'OTINWISRCDT050', ip: '172.24.185.103', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_71'
*** Element info: {Using=xpath, value=.//*[#id='frmPDAuditReports']//table[#class='PageHeading']/tbody/tr/td}
Session ID: c613b73a-e941-4847-ae49-06bcae108cdd
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{platform=WINDOWS, javascriptEnabled=true, elementScrollBehavior=1, ignoreZoomSetting=true, enablePersistentHover=false, ie.ensureCleanSession=true, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=9, ie.usePerProcessProxy=false, ignoreProtectedModeSettings=true, cssSelectorsEnabled=true, requireWindowFocus=true, initialBrowserUrl=http://localhost:47437/, handlesAlerts=true, ie.forceCreateProcessApi=false, nativeEvents=true, browserAttachTimeout=0, ie.browserCommandLineSwitches=, takesScreenshot=true}]
ERROR[CreatePolicyApprovalDeviationRequestPageObjects]: PageHeading():Element not found: Null Returned
ERROR[CreatePolicyApprovalDeviationRequestPageServices]: PageHeading(): Page Heading element not found !!
ERROR[CreatePolicyApprovalDeviationRequestPageServices]: PageHeading(): 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:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:605)
at org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:383)
at org.openqa.selenium.remote.RemoteWebDriver.findElementsByXPath(RemoteWebDriver.java:459)
at org.openqa.selenium.By$ByXPath.findElements(By.java:353)
at org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:346)
at Utilities.ObjectRetriever.customElementWaitWithTimeoutWithProperties(ObjectRetriever.java:172)
at PageObjects.CreatePolicyApprovalDeviationRequestPageObjects.pageHeading(CreatePolicyApprovalDeviationRequestPageObjects.java:34)
at ServicesOfPage.CreatePolicyApprovalDeviationRequestPageServices.getPageHeading(CreatePolicyApprovalDeviationRequestPageServices.java:58)
at Tests.isNavigatedToCreatePolicyApprovalDeviationRequestPage.compareHomePageHeading(isNavigatedToCreatePolicyApprovalDeviationRequestPage.java:32)
at Execution.TestExecution.TC(TestExecution.java:254)
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)
I'm finding it extremely difficult to figure out what is/are the possible things that went wrong for this particular execution,Help me!
Any help will be appreciated !!
I can see three reasons why it doesn't work.
1) Wrong XPath:
I recommend installing Google Chrome. In Chrome when you Inspect Element, you can right click on an element, and directly copy XPath.
2) Page heading gets loaded asynchronously:
Are you sure the website doesn't load your element asynchronously? Try disabling JavaScript and load the website to see if the element is there.
3) Browser error?:
This can sometimes happen, and IE is not a very good browser for Selenium. You could try Firefox or headless browser like PhantomJS.

driver.get not working in Selenium Webdriver, Java

When using driver.get on a certain website (driver.get("http://steamcommunity.com/market/search?appid=730")), I get this error:
Exception in thread "main" org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: Exception invoking fireEvent
Build info: version: '2.45.0', revision: '5017cb8', time: '2015-02-26 23:59:50'
System info: host: 'daltonpc', ip: '10.0.0.2', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
Driver info: driver.version: HtmlUnitDriver
at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:504)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:480)
at org.openqa.selenium.example.FinderClass.findOtherWeapon(FinderClass.java:60)
at org.openqa.selenium.example.Main.main(Main.java:20)
Caused by: com.gargoylesoftware.htmlunit.ScriptException: Exception invoking fireEvent
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:705)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:620)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:637)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:612)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:1001)
at com.gargoylesoftware.htmlunit.javascript.host.EventListenersContainer.executeEventListeners(EventListenersContainer.java:179)
at com.gargoylesoftware.htmlunit.javascript.host.EventListenersContainer.executeBubblingListeners(EventListenersContainer.java:239)
at com.gargoylesoftware.htmlunit.javascript.host.Node.fireEvent(Node.java:824)
at com.gargoylesoftware.htmlunit.javascript.host.Node.fireEvent(Node.java:748)
at com.gargoylesoftware.htmlunit.html.HtmlElement$1.run(HtmlElement.java:920)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:620)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.html.HtmlElement.fireEvent(HtmlElement.java:925)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeEventHandlersIfNeeded(HtmlPage.java:1298)
at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:290)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:475)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:342)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:407)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:491)
... 3 more
Caused by: java.lang.RuntimeException: Exception invoking fireEvent
at net.sourceforge.htmlunit.corejs.javascript.MemberBox.invoke(MemberBox.java:148)
at net.sourceforge.htmlunit.corejs.javascript.FunctionObject.call(FunctionObject.java:448)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1531)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:798)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:411)
at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:309)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3057)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:103)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$4.doRun(JavaScriptEngine.java:630)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:690)
... 22 more
Caused by: com.gargoylesoftware.htmlunit.ScriptException: illegal radix 0. (http://steamcommunity-a.akamaihd.net/public/shared/javascript/shared_global.js?v=BESEFoKTgss6&l=english#1358)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:705)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:620)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:637)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:612)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:1001)
at com.gargoylesoftware.htmlunit.javascript.host.EventListenersContainer.executeEventListeners(EventListenersContainer.java:179)
at com.gargoylesoftware.htmlunit.javascript.host.EventListenersContainer.executeBubblingListeners(EventListenersContainer.java:239)
at com.gargoylesoftware.htmlunit.javascript.host.Node.fireEvent(Node.java:814)
at com.gargoylesoftware.htmlunit.javascript.host.Node.fireEvent(Node.java:748)
at com.gargoylesoftware.htmlunit.javascript.host.EventNode.fireEvent(EventNode.java:396)
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 net.sourceforge.htmlunit.corejs.javascript.MemberBox.invoke(MemberBox.java:120)
... 32 more
Caused by: net.sourceforge.htmlunit.corejs.javascript.EvaluatorException: illegal radix 0. (http://steamcommunity-a.akamaihd.net/public/shared/javascript/shared_global.js?v=BESEFoKTgss6&l=english#1358)
at com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter.runtimeError(StrictErrorReporter.java:81)
at net.sourceforge.htmlunit.corejs.javascript.Context.reportRuntimeError(Context.java:1047)
at net.sourceforge.htmlunit.corejs.javascript.Context.reportRuntimeError(Context.java:1094)
at net.sourceforge.htmlunit.corejs.javascript.Context.reportRuntimeError1(Context.java:1062)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.numberToString(ScriptRuntime.java:813)
at net.sourceforge.htmlunit.corejs.javascript.NativeNumber.execIdCall(NativeNumber.java:129)
at net.sourceforge.htmlunit.corejs.javascript.IdFunctionObject.call(IdFunctionObject.java:89)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1531)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:798)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$4.doRun(JavaScriptEngine.java:630)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:690)
... 47 more
It works fine with other urls, and it also worked with this one until I enabled javascript by putting true in WebDriver driver = new HtmlUnitDriver(true);. I needed to do this because my program wasn't working properly without javascript, and it seems like this steam community market page requires javascript in order to access it, even by just typing in the url. What am I doing wrong?
Using a user agent will solve the ScriptException. Use DesiredCapabilties to do so. See below code:
DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
capabilities.setBrowserName("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20160101 Firefox/66.0");
HtmlUnitDriver driver = new HtmlUnitDriver(capabilities);
driver.setJavascriptEnabled(true);
driver.get("http://steamcommunity.com/market/search?appid=730");
System.out.println(driver.getPageSource());
This works fine.
Although, an alternate solution would be to use PhantomJSDriver which I found to be much better at locating elements.
Download PhantomJS.exe file and set the exe's file path as PHANTOMJS_EXECUTABLE_PATH_PROPERTY
public class CopyOfTest1
{
PhantomJSDriver driver;
WebDriverWait wait;
DesiredCapabilities capabilities;
CopyOfTest1()
{
//set binary path of phantomJS driver
capabilities = new DesiredCapabilities();
capabilities.setJavascriptEnabled(true);
capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "drivers/phantomjs.exe");
capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_SETTINGS_PREFIX,"Y");
capabilities.setCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:16.0) Gecko/20121026 Firefox/16.0");
//intialize driver and set capabilties
driver = new PhantomJSDriver(capabilities);
//intitlaize webdriverwait class
wait = new WebDriverWait(driver, 30);
}
void start()
{
driver.get("http://steamcommunity.com/market/search?appid=730");
System.out.println(driver.getPageSource());
driver.quit();
}
public static void main(String[] args) throws Exception
{
new CopyOfTest1().start();
}
}
You are missing double quotation " in url. Try the following
driver.get("http://steamcommunity.com/market/search?appid=730")

StaleElementReferenceException: determining which element is causing the exception

I've done some pretty thorough digging and am having trouble nailing down exactly which element is causing this exception to be thrown. I'm using Java and Selenium 2 and have recently taken over a fairly large test suite to maintain. Instead of blindly placing fluent waits in and around the failing lines of code, I'd like to actually determine which elements are causing the issue.
I've though about breaking a bunch of the single-line logic into more lines of code to help nail it down but since these random failure are intermittent and all over the place, I'm trying to find a way to get the actual name of the element or locator in the stack trace.
Is this possible or do I have to do a bunch of refactoring on the code end of things?
Here is an example stack trace:
Starting ChromeDriver (v2.3) on port 24902
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=30.0.1599.101)
(Driver info: chromedriver=2.3,platform=Mac OS X 10.8.5 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 5 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.33.0', revision: '4ecaf82108b2a6cc6f006aae81961236eba93358', time: '2013-05-22 12:00:17'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.8.5', java.version: '1.7.0_21'
Session ID: f3e5d2c3eb54afc2fcaacc1c663435e9
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=MAC, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={chromedriverVersion=2.3}, rotatable=false, locationContextEnabled=true, version=30.0.1599.101, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, applicationCacheEnabled=false, takesScreenshot=true}]
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:525)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:191)
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.findElements(RemoteWebElement.java:187)
at org.openqa.selenium.remote.RemoteWebElement.findElementsByCssSelector(RemoteWebElement.java:240)
at org.openqa.selenium.By$ByCssSelector.findElements(By.java:417)
at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:163)
at com.xmatters.webui.pages.home.developer.managerelevanceengines.formdetails.layoutsections.CustomSectionScreen.rowPropertyIsInCustomSection(CustomSectionScreen.java:54)
at com.xmatters.webui.pages.home.developer.managerelevanceengines.formdetails.layoutsections.CustomSectionScreen.editNameForProperty(CustomSectionScreen.java:90)
at com.xmatters.webdriver.tests.REBProperties_BooleanTest.confirmBooleanPropertyNameCanBeEditedOnLayoutTab(REBProperties_BooleanTest.java:526)
The code on the suspect line is in this helper function.
Line 54 is the line containing List<WebElement>...
public Integer rowPropertyIsInCustomSection(String propertyName) {
wait.until(ExpectedConditions.presenceOfElementLocated(customSectionLocator));
WebElement customSection = driver.findElement(customSectionLocator);
//wait until properties are present in custom section
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(propertiesInCustomSectionLocator));
List<WebElement> propertiesInCustomSection = customSection.findElements(propertyNameLocatorInCustomSection);
By propertyNameLoc = By.id("propertyName");
for (int i = 0; i < propertiesInCustomSection.size(); i++) {
wait.until(ExpectedConditions.visibilityOfElementLocated(propertyNameLoc));
String propName = propertiesInCustomSection.get(i).findElement(propertyNameLoc).getText();
if (propName.equals(propertyName)) {
return i;
}
}
return null;
Apologies if this has been answered elsewhere but I'm having a tough time nailing this one down with so little to work with in the stack trace. This code was all written by someone else so dissecting it piece by piece is kind of a last resort for me at the moment.
Thanks in advance for any pointers.
Darwin.
I'm pretty sure it's the customSection element.
WebElement#findElements() will definitely not throw a StaleElementReferenceException on any of the freshly found elements (that would be a bad Selenium bug).
As said in WebElement docs, it will throw on most of the methods called on a previously found WebElement. Therefore when you try to invoke findElements() on an element, it performs a freshness check which fails for some reason.
Before searching for customSection, try to wait for some of the its properties to show up. It's possible that when adding properties to the section, the element is discarded and replaced by a new one. Or you can try one of the techniques described here, namely the NeverStaleWebElement.

Categories

Resources