PhantomJS selenium NoSuchElementException - java

I have created a web crawler with Selenium (using selenium-server-standalone-2.47.1.jar) and phantomJs (phantomjs -v returns 1.9.0 on Ubuntu 14.04). The code was working fine with both with FirefoxDriver and PhantomJSDriver on Windows 10, but only works with FirefoxDriver under Ubuntu 14.04.
Sample code below:
public static void main(String[] args) {
DesiredCapabilities DesireCaps = new DesiredCapabilities();
DesireCaps.setCapability("phantomjs.binary.path", "/usr/lib/phantomjs/phantomjs");
WebDriver driver=new PhantomJSDriver(DesireCaps);
String Url = "https://xxx";
driver.get(Url);
WebElement rootWebElement = driver.findElement(By.id("main"));
List<WebElement> parentElements = rootWebElement.findElements(By.tagName("li"));
//243 , 240 (previous)
for (int i = 106; i < parentElements.size(); i++) {
WebElement href =parentElements.get(i).findElement(By.tagName("z"));
if(href!=null){
Scanner scanner = new Scanner(href.getAttribute("href"));
try {
scanner.parseXML(href.getAttribute("href"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
If you open the provided URL's source.... you can easily see that the tag with id="main" exists...
Stack Trace:
PhantomJS is launching GhostDriver...
[INFO - 2015-08-13T14:15:57.720Z] GhostDriver - Main - running on port 8677
[INFO - 2015-08-13T14:15:58.361Z] Session [d17a3cc0-41c5-11e5-bedb-6fa39763a2c0] - CONSTRUCTOR - Desired Capabilities: {"phantomjs.binary.path":"/usr/lib/phantomjs/phantomjs"}
[INFO - 2015-08-13T14:15:58.370Z] Session [d17a3cc0-41c5-11e5-bedb-6fa39763a2c0] - CONSTRUCTOR - Negotiated Capabilities: {"browserName":"phantomjs","version":"1.9.0","driverName":"ghostdriver","driverVersion":"1.0.3","platform":"linux-unknown-32bit","javascriptEnabled":true,"takesScreenshot":true,"handlesAlerts":false,"databaseEnabled":false,"locationContextEnabled":false,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"cssSelectorsEnabled":true,"webStorageEnabled":false,"rotatable":false,"acceptSslCerts":false,"nativeEvents":true,"proxy":{"proxyType":"direct"}}
[INFO - 2015-08-13T14:15:58.371Z] SessionManagerReqHand - _postNewSessionCommand - New Session Created: d17a3cc0-41c5-11e5-bedb-6fa39763a2c0
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Error Message => 'Unable to find element with id 'main''
caused by Request => {"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"29","Content-Type":"application/json; charset=utf-8","Host":"localhost:8677","User-Agent":"Apache-HttpClient/4.4.1 (Java/1.7.0_79)"},"httpVersion":"1.1","method":"POST","post":"{\"using\":\"id\",\"value\":\"main\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/d17a3cc0-41c5-11e5-bedb-6fa39763a2c0/element"}
Command duration or timeout: 281 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 03:03:16'
System info: host: 'Vmbox', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'i386', os.version: '3.19.0-25-generic', java.version: '1.7.0_79'
*** Element info: {Using=id, value=main}
Session ID: d17a3cc0-41c5-11e5-bedb-6fa39763a2c0
Driver info: org.openqa.selenium.phantomjs.PhantomJSDriver
Capabilities [{platform=LINUX, acceptSslCerts=false, javascriptEnabled=true, browserName=phantomjs, rotatable=false, driverVersion=1.0.3, locationContextEnabled=false, version=1.9.0, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=false, browserConnectionEnabled=false, proxy={proxyType=direct}, nativeEvents=true, webStorageEnabled=false, driverName=ghostdriver, 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:526)
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:595)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:389)
at org.openqa.selenium.By$ById.findElement(By.java:215)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:340)
at LinkScanner.main(LinkScanner.java:27)
Caused by: org.openqa.selenium.remote.ScreenshotException: Screen shot has been taken
Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 03:03:16'
System info: host: 'Vmbox', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'i386', os.version: '3.19.0-25-generic', java.version: '1.7.0_79'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:138)
... 6 more
Caused by: org.openqa.selenium.NoSuchElementException: Error Message => 'Unable to find element with id 'main''
caused by Request => {"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"29","Content-Type":"application/json; charset=utf-8","Host":"localhost:8677","User-Agent":"Apache-HttpClient/4.4.1 (Java/1.7.0_79)"},"httpVersion":"1.1","method":"POST","post":"{\"using\":\"id\",\"value\":\"main\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/d17a3cc0-41c5-11e5-bedb-6fa39763a2c0/element"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 03:03:16'
System info: host: 'Vmbox', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'i386', os.version: '3.19.0-25-generic', java.version: '1.7.0_79'
Driver info: driver.version: unknown

Post my comment as answer :)
You need to install PhantomJS 1.9.8 from https://bitbucket.org/ariya/phantomjs/downloads

Related

Using Selenium Grid to run Safari on MacOS Mojave

I'm trying to do a basic test using Selenium Grid to start Safari on a MacOS.
I have registered the node and its appears in my hub as the following.
Hub Confirmating node is up
browserTimeout: 0
debug: false
host: 10.120.45.211
port: 5558
role: node
timeout: 1800
cleanUpCycle: 5000
maxSession: 5
capabilities: Capabilities {browserName: Safari, maxInstances: 1,
platform: MAC, platformName: MAC, seleniumProtocol: WebDriver,
server:CONFIG_UUID: 1ba7b7b4-556c-430a-ab84-157...}
downPollingLimit: 2
hub: http://10.120.45.245:4444/grid/register
id: http://10.120.45.211:5558
nodePolling: 5000
nodeStatusCheckTimeout: 5000
proxy: org.openqa.grid.selenium.proxy.DefaultRemoteProxy
register: true
registerCycle: 5000
remoteHost: http://10.120.45.211:5558
unregisterIfStillDownAfter: 60000
I understand that SafariDriver is now available directly within macOS and i'm using these steps to make sure it setup correctly.
If you haven’t already done so, make the Develop menu available. Choose Safari > Preferences, and on the Advanced tab, select “Show Develop menu in menu bar.” For details, see Safari Help.
Choose Develop > Allow Remote Automation.
Authorize safaridriver to launch the XPC service that hosts the local web server. To permit this, manually run /usr/bin/safaridriver once and follow the authentication prompt.
This is my JAVA code:
package SeleniumGrid;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class SafariRemoteAccess {
public static void main(String[] args) throws MalformedURLException {
DesiredCapabilities dc = new DesiredCapabilities();
dc.setBrowserName("Safari");
//Point to hub
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), dc);
// Go to website via NODE
driver.get("https://www.hsbc.co.uk/");
driver.quit();
}
}
When I run the program i getting the following message.
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create session from {
"desiredCapabilities": {
"browserName": "Safari",
"server:CONFIG_UUID": "1ba7b7b4-556c-430a-ab84-1574fc7ea584"
},
"capabilities": {
"firstMatch": [
{
"browserName": "Safari",
"server:CONFIG_UUID": "1ba7b7b4-556c-430a-ab84-1574fc7ea584"
}
]
}
}
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'Mishal-Shahs-MacBook-Pro.local', ip: 'fe80:0:0:0:c9b:214f:9f0:2788%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.2', java.version: '1.8.0_202'
Driver info: driver.version: unknown
Command duration or timeout: 198 milliseconds**
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:214)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$errorHandler$0(JsonWireProtocolResponse.java:54)
at org.openqa.selenium.remote.HandshakeResponse.lambda$getResponseFunction$0(HandshakeResponse.java:30)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:126)
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:128)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:74)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:144)
at SeleniumGrid.SafariRemoteAccess.main(SafariRemoteAccess.java:17)
Caused by: org.openqa.selenium.SessionNotCreatedException: Unable to create session from {
"desiredCapabilities": {
"browserName": "Safari",
"server:CONFIG_UUID": "1ba7b7b4-556c-430a-ab84-1574fc7ea584"
},
"capabilities": {
"firstMatch": [
{
"browserName": "Safari",
"server:CONFIG_UUID": "1ba7b7b4-556c-430a-ab84-1574fc7ea584"
}
]
}
}
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'Mishal-Shahs-MacBook-Pro.local', ip: 'fe80:0:0:0:c9b:214f:9f0:2788%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.2', java.version: '1.8.0_202'
Driver info: driver.version: unknown
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'LAPTOP-1MOS5JFR', ip: '10.120.45.245', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_192'
Driver info: driver.version: unknown
at org.openqa.selenium.remote.server.NewSessionPipeline.lambda$null$4(NewSessionPipeline.java:76)
at java.util.Optional.orElseThrow(Optional.java:290)
at org.openqa.selenium.remote.server.NewSessionPipeline.lambda$createNewSession$5(NewSessionPipeline.java:75)
at java.util.Optional.orElseGet(Optional.java:267)
at org.openqa.selenium.remote.server.NewSessionPipeline.createNewSession(NewSessionPipeline.java:73)
at org.openqa.selenium.remote.server.commandhandler.BeginSession.execute(BeginSession.java:65)
at org.openqa.selenium.remote.server.WebDriverServlet.lambda$handle$0(WebDriverServlet.java:235)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Update
This is the code im using to setup the NODE on the MacOS machine:
java -Dwebdriver.safari.driver=/System/Library/CoreServices/SafariSupport.bundle/Contents/MacOS/safaridriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub 10.120.45.245:4444/grid/register -port 5558 -browser "browserName=Safari, platform=MAC, platformName=MAC, maxInstances=1"
It is not clear from your error stack trace if the Selenium Grid is on Mac OS X and to start the Selenium Node you are using the command:
java -Dwebdriver.safari.driver=/System/Library/CoreServices/SafariSupport.bundle/Contents/MacOS/safaridriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub 10.120.45.245:4444/grid/register -port 5558 -browser "browserName=Safari, platform=MAC, platformName=MAC, maxInstances=1"
why would you see the error log as (relates to Selenium Grid):
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'Mishal-Shahs-MacBook-Pro.local', ip: 'fe80:0:0:0:c9b:214f:9f0:2788%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.2', java.version: '1.8.0_202'
Driver info: driver.version: unknown
Then again (first set relates to Mac OS X and second set relates to Windows 10):
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'Mishal-Shahs-MacBook-Pro.local', ip: 'fe80:0:0:0:c9b:214f:9f0:2788%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.2', java.version: '1.8.0_202'
Driver info: driver.version: unknown
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'LAPTOP-1MOS5JFR', ip: '10.120.45.245', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_192'
Driver info: driver.version: unknown
However the command you have used to initiate the Selenium Grid Node is error prone as it contains both:
platform=MAC
platformName=MAC
Assuming the Selenium Grid Node is being initiated from the Windows 10 box the command should be:
java -Dwebdriver.safari.driver=C:\path\to\safaridriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub 10.120.45.245:4444/grid/register -port 5558 -browser "browserName=safari, platform=WINDOWS, maxInstances=1"
Note: Ensure Safari browser is installed within the Windows 10.

How to fix “Permission denied to access property "invoke”"?

Code -
Select Gender = new Select(driver.findElement(By.xpath("//select[#id='gender']")));
Gender.selectByValue("Male");
Error -
`Exception in thread "main" org.openqa.selenium.WebDriverException: **Permission denied to access property "invoke"**
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'COMP2-PC', ip: '192.168.1.9', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_91'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{rotatable=false, raisesAccessibilityExceptions=false, appBuildId=20161123182536, version=50.0.1, platform=XP, proxy=Proxy(), command_id=1.0, specificationLevel=0.0, acceptSslCerts=false, processId=2380.0, browserVersion=50.0.1, platformVersion=6.1, XULappId={ec8030f7-c20a-464f-9b0e-13a3a9e97384}, browserName=firefox, takesScreenshot=true, takesElementScreenshot=true, javascriptEnabled=true, platformName=windows_nt}] Session ID: c1e4da76-9f21-45aa-a1b8-f21a9e8dd088
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.RemoteWebElement.execute
(RemoteWebElement.java:272)
at org.openqa.selenium.remote.RemoteWebElement.getAttribute
(RemoteWebElement.java:124)
at org.openqa.selenium.support.ui.Select.<init>(Select.java:52)
at AppInformationTest.main(AppInformationTest.java:70) `
While trying to automate (Selecting a dropdown value) with selenium webdriver I ran into this problem.
Tools Versions are*:
Java - 1.8.0_91,
Eclipse - Oxygen Release (4.7.0),
Mozilla Firefox-50.01,
Gecko driver-v0.17.0-win64 ....Please help me to sort out!
It is browser specfic issue , try it with Chrome. Follow this link to see more
Reference Link for your issue

Error method not implemented

I'm trying to get the start coordinates and the size of the element in a android app using uiautomator and selenium. I was stuck at this point. The code says that the WebElement is a interface. So I even tried to typecast it but it was saying that was redundant type cast as the return type was RemoteWebElement and it also had an implementation. This is my code and the following error occurs. Can someone please help me out??
130 WebElement webElement = LIST_ELEMENTS_XPATH.findElement(this.elementOperator.getDriver());
131 Rectangle rectangle = webElement.getRect();
132 int listX = rectangle.getX();
133 int listY = rectangle.getY();
134 int listHeight = rectangle.getHeight();
135 int listWidth = rectangle.getWidth();
And this is the error
org.openqa.selenium.WebDriverException: Method has not yet been implemented (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 18 milliseconds
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:32:46'
System info: host: '38c9860577c9', ip: '10.55.22.63', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.4', java.version: '1.8.0_131'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{appPackage=com.amazon.dee.app, deviceScreenSize=1080x1920, networkConnectionEnabled=true, recreateChromeDriverSessions=true, noReset=true, warnings={}, databaseEnabled=false, deviceName=WUJ01NML4S, platform=LINUX, deviceUDID=WUJ01NML4S, appActivity=.Launcher, desired={appActivity=.Launcher, appPackage=com.amazon.dee.app, recreateChromeDriverSessions=true, noReset=true, newCommandTimeout=300, platformName=Android, udid=WUJ01NML4S, deviceName=Android Device}, newCommandTimeout=300, platformVersion=6.0, webStorageEnabled=false, locationContextEnabled=false, takesScreenshot=true, javascriptEnabled=true, deviceModel=F3216, platformName=Android, udid=WUJ01NML4S, deviceManufacturer=Sony}]
Session ID: 4c06d952-bc1b-4afd-9a0c-eb47098dbb4e
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:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:40)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:327)
at io.appium.java_client.DefaultGenericMobileElement.execute(DefaultGenericMobileElement.java:33)
at io.appium.java_client.MobileElement.execute(MobileElement.java:1)
at io.appium.java_client.android.AndroidElement.execute(AndroidElement.java:1)
at org.openqa.selenium.remote.RemoteWebElement.getRect(RemoteWebElement.java:400)
at com.amazon.alexa.comms.testsdk.mobile.alexaapp.pages.comms.conversationthread.ConversationThreadPageAndroid.scrollUp(ConversationThreadPageAndroid.java:131)

org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM

I'm getting "StaleElementReferenceException" when selecting an option from the dropdown and get it as string. I'm very disappointed with the issue for last two days and I didn't get any best suggestion to sort out my issue. I'm very new to selenium, Please help me to sort out this issue.
public static WebElement prepProduct(WebDriver driver) throws InterruptedException
{
WebDriverWait wait = new WebDriverWait(driver,20);
Boolean enable=driver.findElement(By.xpath(".//*[#id='batch-update-prep-owner']")).isEnabled();
if(enable.TRUE)
{
Select whoPrepsMerchant= new Select(driver.findElement(By.xpath(".//*[#id='prep-items']/tr[2]/td[5]/select")));
whoPrepsMerchant.selectByIndex(new Random().nextInt(whoPrepsMerchant.getOptions().size()));
String merchant=whoPrepsMerchant.getFirstSelectedOption().getText();
Thread.sleep(3000);
String whoPrepsvalue=(driver.findElement(By.xpath(".//*[#id='prep-items']/tr[2]/td[7]/span"))).getText();
System.out.println("outer");
if(merchant.equalsIgnoreCase("Amazon"))
{
System.out.println("inner");
if(!whoPrepsvalue.equalsIgnoreCase("--"))
{
System.out.println("innerone");
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='continue-plan']")).click();
}
}
else
{
if(whoPrepsvalue.equalsIgnoreCase("--"))
{
System.out.println("innertwo");
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='continue-plan']")).click();
}
}
}
else
{
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='continue-plan']")).click();
}
return element;
}
Error Log:
org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM
Command duration or timeout: 15 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.0.0-beta4', revision: '3169782', time: '2016-09-29 10:29:23 -0700'
System info: host: '7531HY1', ip: '10.45.183.77', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_111'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=45.4.0, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 2eb3cd2b-e2e0-4efb-8b4c-3eb08f00ed45
*** Element info: {Using=tag name, value=option}
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:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:636)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:284)
at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:203)
at org.openqa.selenium.remote.RemoteWebElement.findElementsByTagName(RemoteWebElement.java:280)
at org.openqa.selenium.By$ByTagName.findElements(By.java:327)
at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:179)
at org.openqa.selenium.support.ui.Select.getOptions(Select.java:70)
at org.openqa.selenium.support.ui.Select.getFirstSelectedOption(Select.java:94)
at NAGamma.SellerCentralPOM.prepProduct(SellerCentralPOM.java:85)
at NAGamma.Regression.main(Regression.java:40)
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:100)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:646)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:811)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1137)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:753)
at org.testng.TestRunner.run(TestRunner.java:607)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:368)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:363)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:321)
at org.testng.SuiteRunner.run(SuiteRunner.java:270)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1284)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)
at org.testng.TestNG.runSuites(TestNG.java:1124)
at org.testng.TestNG.run(TestNG.java:1096)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
Caused by: org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.0.0-beta4', revision: '3169782', time: '2016-09-29 10:29:23 -0700'
System info: host: '7531HY1', ip: '10.45.183.77', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_111'
Driver info: driver.version: unknown
at <anonymous class>.fxdriver.cache.getElementAt(resource://fxdriver/modules/web-element-cache.js:9531)
at <anonymous class>.Utils.getElementAt(file:///C:/Users/kesavamp/AppData/Local/Temp/anonymous980588199586178216webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:9916)
at <anonymous class>.FirefoxDriver.prototype.findElementsInternal_(file:///C:/Users/kesavamp/AppData/Local/Temp/anonymous980588199586178216webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:11205)
at <anonymous class>.FirefoxDriver.prototype.findChildElements(file:///C:/Users/kesavamp/AppData/Local/Temp/anonymous980588199586178216webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:11226)
at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/kesavamp/AppData/Local/Temp/anonymous980588199586178216webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12698)
at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/kesavamp/AppData/Local/Temp/anonymous980588199586178216webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12703)
at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/kesavamp/AppData/Local/Temp/anonymous980588199586178216webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12645)
Try this
Declare at the global level
WebDriverWait wait = new WebDriverWait(driver, 5);
Before selecting option from Drop-down
// while the following loop runs, the DOM changes -
// page is refreshed, or element is removed and re-added
wait.until(presenceOfElementLocated(By.id("container-element")));
// now we're good - let's click the element
For selecting option from Drop-down.
driver.findElement(By.id("foo")).click();
You can use:
wait.until(ExpectedConditions.refreshed(ExpectedConditions.visibilityOf(Element)));
Please verify and let me know if this is working fine for you...

Error while executing the selenium program

package Com.Automation;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Second_Findelements {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.get("http://www.google.com");
System.out.println(driver.getCurrentUrl());
System.out.println(driver.getTitle());
driver.findElement(By.name("q")).sendKeys("gmail");
driver.findElement(By.xpath("//a[(text()='Gmail - Google']")).click();
driver.quit();
}
}
Error is:
Exception in thread "main" org.openqa.selenium.InvalidSelectorException:
The given selector //a[(text()='Gmail - Google'] is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Unable to locate an element with the xpath expression //a[(text()='Gmail - Google'] because of the following error:
SyntaxError: The expression is not a legal expression.
Command duration or timeout: 30 milliseconds
For documentation on this error, please visit:
http://seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'shaheena-PC', ip: '100.68.111.156', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_51'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=43.0, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 62a7b699-fabb-4742-82dc-6f7785f33275
*** Element info: {Using=xpath, value=//a[(text()='Gmail - Google']}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:353)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:490)
at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:345)
at Com.Automation.Second_Findelements.main(Second_Findelements.java:23)
Caused by: org.openqa.selenium.InvalidSelectorException: The given selector //a[(text()='Gmail - Google'] is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Unable to locate an element with the xpath expression //a[(text()='Gmail - Google'] because of the following error:
SyntaxError: The expression is not a legal expression.
For documentation on this error, please visit: http://seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'shaheena-PC', ip: '100.68.111.156', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_51'
Driver info: driver.version: unknown
at <anonymous class>.FirefoxDriver.annotateInvalidSelectorError_(file:///C:/Users/shaheena/AppData/Local/Temp/anonymous3401694128124177427webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:10633)
at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/shaheena/AppData/Local/Temp/anonymous3401694128124177427webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:10664)
at <anonymous class>.FirefoxDriver.prototype.findElement(file:///C:/Users/shaheena/AppData/Local/Temp/anonymous3401694128124177427webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:10668)
at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/shaheena/AppData/Local/Temp/anonymous3401694128124177427webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12534)
at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/shaheena/AppData/Local/Temp/anonymous3401694128124177427webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12539)
at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/shaheena/AppData/Local/Temp/anonymous3401694128124177427webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12481)
You have write wrong xpath :
//a[(text()='Gmail - Google']
True xpath is :
//a[text()='Gmail - Google']
You have add extra "("
If you want to use contains
//a[contains(text(),'Gmail')]
Use unique text instead of Gmail in above xpath

Categories