Here is the scenario:
Click a link that opens up to a new tab.
Call getWindowHandles() and switch to the new tab.
Use JavaScript Executor to open up the Print PopUp
Call getWindowHandles() again to switch focus to the Print PopUp
This second getWindowHandles() call is causing my script to timeout and I'm not sure why. Could someone help me figure out what's going on with this second call? Everything is working as expected until step 4
link.click();
ArrayList<String> handles2 = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(handles2.get(1));
((JavascriptExecutor)driver).executeScript("window.print()");
ArrayList<String> handles3 = new ArrayList<String> (driver.getWindowHandles());
Maybe useful information:
Error Message:
org.openqa.selenium.ScriptTimeoutException: script timeout
(Session info: chrome=86.0.4240.183)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: '', ip: '', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_261'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: true, browserName: chrome, browserVersion: 86.0.4240.183, chrome: {chromedriverVersion: 86.0.4240.22 (..., userDataDir: C:\Users\AppData\L...}, goog:chromeOptions: {debuggerAddress: localhost:}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:virtualAuthenticators: true}
The issue was the print dialog causing the main thread to lock out.
You are able to use the Robot class as suggested by #pcalkins. But I used the SetTimeout function.
Reference: ChromeDriver - Timeout when trying to print page with javascript
Related
I am trying to run the following code:
WebElement body = driver.findElement(By.xpath("/html/body"));
js.executeScript("var injector = window.angular.element(argument[0]).injector(); var $http = injector.get('$http'); return ($http.pendingRequests.length === 0);",body);
I however get the following error:
org.openqa.selenium.JavascriptException: javascript error: Cannot read properties of undefined (reading 'element')
(Session info: chrome=103.0.5060.134)
Build info: version: '4.2.2', revision: '683ccb65d6'
System info: host: 'DESKTOP-UPVJF2U', ip: '192.168.0.132', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '18.0.1.1'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Command: [c6b4ce36aa115d9746065cead6c3271b, executeScript {script=var injector = window.angular.element(argument[0]).injector(); var $http = injector.get('$http'); return ($http.pendingRequests.length === 0);, args=[{ELEMENT=a0c33e06-9db9-49ed-984f-535b6bc72f7a, element-6066-11e4-a52e-4f735466cecf=a0c33e06-9db9-49ed-984f-535b6bc72f7a}]}]
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 103.0.5060.134, chrome: {chromedriverVersion: 103.0.5060.134 (8ec6fce403b..., userDataDir: C:\Users\win10\AppData\Loca...}, goog:chromeOptions: {debuggerAddress: localhost:53279}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: WINDOWS, proxy: Proxy(), se:cdp: ws://localhost:53279/devtoo..., se:cdpVersion: 103.0.5060.134, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: c6b4ce36aa115d9746065cead6c3271b
at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:200)
at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:133)
at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:53)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:184)
at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:167)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:142)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:588)
at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:522)
at com.vilcart.app.CustomerCreation.testCreation(CustomerCreation.java:118)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
... Removed 28 stack frames
Can you please let me know how i could resolve this issue?
Since you want to get arguments list element by index try to replace
argument[0]
with
arguments[0]
#suhail shaik You can try the following, assuming you want to check if all the pending $http requests are served by Angular in the background.
String angularReady = "return angular.element(document).injector().get('$http').pendingRequests.length === 0";
boolean isAngularReady = (boolean)js.executeScript(angularReady);
I have gone through this link which helped me find a solution. This has a way to put wait for angular version 5 which is working for my current angular version 11.
https://www.swtestacademy.com/selenium-wait-javascript-angular-ajax/
I am currently testing the UI of a PEGA application whereas I have stumbled on an issue where I am clicking a button that in its turn saves an item and closes the frame. When click method is finished it is still looking for frame y but stands on frame x, so it crashes.
The issues followed by this is when using:
driver.findElement(By.x("selector")).click();
frame is switching and in the framework its still trying to locate the previous active frame (which is not visible at this time).
Im on frame PegaGadget2Ifr but ends up on PegaGadget1Ifr curing click.
This is what code im running:
public void saveProjectAsDraft(){
Project_page pp = new Project_page(FDMPortal.getActiveFrameId(true), testEnv);
FDMObjectsBean.setProject_page(pp);
pp.saveDraft();
}
public Workplace_details_page saveDraft(){
findElement(SAVE_DRAFT).click();
return new Workplace_details_page(getActiveFrameId(true),testEnv);
}
getting this error message.
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#PegaGadget2Ifr"}
(Session info: chrome=99.0.4844.74)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
os.version: '10.0', java.version: '1.8.0_312'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 99.0.4844.74, chrome: {chromedriverVersion: 99.0.4844.51 (d537ec02474b5..., userDataDir: x, goog:chromeOptions: {debuggerAddress: localhost:63949}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: x
*** Element info: {Using=id, value=PegaGadget2Ifr}
at sun.reflect.GeneratedConstructorAccessor16.newInstance(Unknown Source)
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:552)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:372)
at org.openqa.selenium.By$ById.findElement(By.java:188)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at com.pega.framework.PegaWebDriverImpl.switchToActiveFrame(PegaWebDriverImpl.java:613)
at com.pega.framework.PegaWebElementImpl.click(PegaWebElementImpl.java:513)
at com.pega.framework.PegaWebElementImpl.click(PegaWebElementImpl.java:407)
at com.pega.crm.workobjects.Project_page.saveDraft(Project_page.java:166)
at stepdefs.WorkplaceStepDefs.saveProjectAsDraft(WorkplaceStepDefs.java:390)```
First switch to the frame where the element is present and then perform activity on the element.
Use one of the available method
switchTo().frame(Index)
switchTo().frame(Web Element)
switchTo().frame(Id or name)
As the previous frame PegaGadget2Ifr closes, an ideal approach would be to switch to the default Content first:
driver.switchTo().defaultContent();
and then attempt to switch to PegaGadget1Ifr frame.
This question already has answers here:
An error has occured in 'site url': Uncaught TypeError: Cannot read property 'getColomnSet' of undefined with Selenium and Python
(2 answers)
"unknown error: cannot read property 'scrollleft' of null" in Chrome using selenium
(1 answer)
Closed 2 years ago.
enter image description here Facing Below error while taking (org.openqa.selenium.JavascriptExecutor)
String style = "";
style = (String) ((JavascriptExecutor) driver)
.executeScript("return document.getElementById(\"modalLayer\").getAttribute(\"style\")");
org.openqa.selenium.JavascriptException: javascript error: Cannot read property 'getAttribute' of null (Session info: headless chrome=80.0.3987.116) Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53' System info: host: 'cloudappnode1.chainsys.com', ip: '192.168.57.140', os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0-693.el7.x86_64', java.version: '11.0.5' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 80.0.3987.116, chrome: {chromedriverVersion: 80.0.3987.106 (f68069574609..., userDataDir: /tmp/.com.google.Chrome.SYBV2k}, goog:chromeOptions: {debuggerAddress: localhost:41272}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify} Session ID: f574977f80da997e421f3783bb669
Please try the below code. Hope so that helps you. I have tested at my end and it is working fine.
JavascriptExecutor executor = (JavascriptExecutor) driver;
String data = String.valueOf(executor.executeScript(
"var styledata = document.getElementById('modalLayer').getAttribute('style');" + "return styledata;"));
System.out.println(data);
I am trying of different ways to select a specific button using seleninum webdriver with java but unfortunately, nothing is working.
When I tested using the Selenium IDE is working. I copied the same xpath, for example, but when I try to test in my java application nothing is working. I tried using different ways, By.cssSelector and By.path.
This is my html:
<section class="fd-section"><fd-action-bar><div class="fd-action-bar"><fd-action-bar-header class="fd-action-bar__header"><fd-action-bar-title><h1 class="fd-action-bar__title"> Applications </h1></fd-action-bar-title></fd-action-bar-header><fd-action-bar-actions class="fd-action-bar__actions"><y-list-search _nghost-c4="" hidden=""><!----><!----><div _ngcontent-c4="" clickoutsideevents="click,mousedown" excludebeforeclick="true" class="ng-star-inserted"><!----><button _ngcontent-c4="" fd-button="" class="fd-button xyz-icon--search fd-button--light ng-star-inserted"></button><!----></div></y-list-search><y-list-filter _nghost-c5="" hidden=""><!----></y-list-filter><!----><button class="open-create-namespace-modal fd-button xyz-icon--add ng-star-inserted" fd-button=""> Create Application </button></fd-action-bar-actions></div></fd-action-bar></section>
I need to select the button with the text " Create Application ".
When I created a test using Selenium IDE the xpath for this button is:
//button[contains(.,' Create Application')]
Basically, my java code is:
public WebElement wElement;
wElement = driver.findElement(By.xpath("//button[contains(.,' Create Application')]"));
wElement.click();
This is the exception message:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(.,' Create Application')]"}
(Session info: chrome=76.0.3809.100)
(Driver info: chromedriver=72.0.3626.69 (3c16f8a135abc0d4da2dff33804db79b849a7c38),platform=Mac OS X 10.14.6 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'C02WW0BZHTD8', ip: 'fe80:0:0:0:8f6:17e1:1a28:1e23%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.6', java.version: '1.8.0_171'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 72.0.3626.69 (3c16f8a135abc..., userDataDir: /var/folders/2r/99nyn7t16cz...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:60374}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: MAC, platformName: MAC, proxy: Proxy(), rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 76.0.3809.100, webStorageEnabled: true}
Session ID: b2341899cd9b62b0169b02371aaa3018
*** Element info: {Using=xpath, value=//button[contains(.,' Create Application')]}
When this piece of code is being executed, is the button loaded into the page already?
{implicit: 0, pageLoad: 300000, script: 30000}, suggests that the driver will not implicitly wait for finding any elements. i.e. if the element is not available, it will throw the exception immediately.
Try driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); before you attempt to find the button.
Also try using below locators -
//button[contains(.,'Create Application')]
//button[contains(text(),'Create Application')]
If none of the above works, please can you provide a URL (if it is public)
Also check whether the button is inside a frame.
You can use JavascriptExecutor interface in this case and try to click the button.
WebElement element = driver.findElement(By.xpath("//button[contains(text(),'Create Application')]"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
Also give a try with WebDriverWait
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Create Application')]"))).click();
The desired element is an Angular element so to locate the element you have to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("fd-action-bar-actions.fd-action-bar__actions button.open-create-namespace-modal.fd-button.xyz-icon--add.ng-star-inserted"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='open-create-namespace-modal fd-button xyz-icon--add ng-star-inserted' and contains(., 'Create Application')]"))).click();
Additional Considerations
Ensure that:
JDK is upgraded to current levels JDK 8u212.
Selenium is upgraded to current levels Version 3.141.59.
ChromeDriver is updated to current ChromeDriver v76.0 level.
Chrome is updated to current Chrome Version 76.0 level. (as per ChromeDriver v76.0 release notes)
Here you can find a detailed discussion on NoSuchElementException, Selenium unable to locate element
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm having trouble with my Explicit Wait not always working. They will randomly fail, and I'm not sure why. I'm hitting element not found, or Stale Element. What can I do to make them more reliable?
public class FrameRegisterAccount extends BasicTests
{
// Generates Email
String userName = ""+(int)(Math.random()*Integer.MAX_VALUE);
String emailID = "Otto"+userName+"#gmail.com";
#Test (priority=1)
public void NewAccount() throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 15, 2500L);
WebElement signButton = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#class='button-sign']")));
signButton.click();
log.info("New Account Creation Screen Opened");
// Fill out Form
WebElement nameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("first_name")));
nameField.sendKeys("Otto");
driver.findElement(By.name("last_name")).sendKeys("Mation Tester");
driver.findElement(By.name("phone_number")).sendKeys("555-555-3231");
driver.findElement(By.name("listings")).sendKeys("4");
// Enter Email and Password
driver.findElement(By.xpath("//input[#name='email']")).clear();
driver.findElement(By.xpath("//input[#name='email']")).sendKeys(emailID);
driver.findElement(By.xpath("//input[#name='password']")).clear();
driver.findElement(By.xpath("//input[#name='password']")).sendKeys("password");
// Click buttons
driver.findElement(By.xpath("//div[#class='input input-term']//div[#class='checkbox-icon']")).click();
driver.findElement(By.xpath("//span[contains(text(),'Sign Up')]")).click();
Thread.sleep(3000);
log.info("New Account Created");
}
#Test (priority=2)
public void ChangePassword() {
// Wait for Dashboard Button
WebDriverWait wait = new WebDriverWait(driver, 15, 2500L);
WebElement dashButton = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(#class,'success-dashboard')]")));
dashButton.click();
log.info("Go to Dashboard Button Pressed");
// Change Password
WebElement proNameX = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='sidebar-top-item']")));
proNameX.click();
WebElement changePass = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#id='nf-change-password-btn']")));
changePass.click();
//driver.findElement(By.xpath("//div[#id='nf-change-password-btn']")).click();
driver.findElement(By.name("old_password")).sendKeys("password");
driver.findElement(By.name("new_password")).sendKeys("wordpass");
driver.findElement(By.name("new_password2")).sendKeys("wordpass");
driver.findElement(By.xpath("//button[#type='button']")).click();
log.info("Password Change Completed");
}
Stacktrace:
org.openqa.selenium.StaleElementReferenceException:
stale element reference: element is not attached to the page document
(Session info: headless chrome=72.0.3626.109)
(Driver info: chromedriver=2.46.628388 (4a34a70827ac54148e092aafb70504c4ea7ae926),platform=Linux 4.14.88-88.76.amzn2.x86_64 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'ip-172-31-36-12.us-west-2.compute.internal', ip: '172.31.36.12', os.name: 'Linux', os.arch: 'amd64', os.version: '4.14.88-88.76.amzn2.x86_64', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.46.628388 (4a34a70827ac54..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:42199}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), rotatable: false, setWindowRect: true, strictFileInteractability: false, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 72.0.3626.109, webStorageEnabled: true}
Session ID: 1a448c188bc68362fa3dc7858ee770b3
at registerAuto.FrameRegisterAccount.ChangePassword(FrameRegisterAccount.java:57)
Stack 2:
org.openqa.selenium.TimeoutException:
Expected condition failed: waiting for element to be clickable: By.xpath: //div[#id='sidebar-top-item'] (tried for 15 second(s) with 2500 milliseconds interval)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'ip-172-31-36-12.us-west-2.compute.internal', ip: '172.31.36.12', os.name: 'Linux', os.arch: 'amd64', os.version: '4.14.88-88.76.amzn2.x86_64', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.46.628388 (4a34a70827ac54..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:42977}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), rotatable: false, setWindowRect: true, strictFileInteractability: false, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 72.0.3626.109, webStorageEnabled: true}
Session ID: 7b255ab6a2cf5b58cf3919904e703b2a
at allStagingAutomation.FrameRegisterAccountStaging.ChangePassword(FrameRegisterAccountStaging.java:55)
StaleElementReference exception comes when the element you are trying to interact is no longer in the dom or has become stale. So, you need to refresh the page and then again fetch the element and it would work.
So, please add driver.navigate().refresh(); line of code before the element on which you are getting the exception and then operate on the element and it would work fine.