Scrolling Webelement using Selenium Webdriver with Java - java

Please help me to handle StaleElementReferanceException.
I am trying to scroll a webelement using action class.
Below is the code:
public void newsSearch() throws StaleElementReferenceException{
driver.get("https://pi.persistent.co.in");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("ui-accordion-1-header-2")).click();
Actions act = new Actions(driver);
int numOfPixels = 2;
WebElement draggablePartOfScrollbar = driver.findElement(By.xpath("//*[#id='ui-accordion-1-panel-2']/div/div[2]/div[2]/div"));
for (int i = 2; i < 50; i = i + numOfPixels) {
act.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0, numOfPixels).release().perform();
System.out.println("Inside for loop");
}
System.out.println("After for loop");
driver.findElement(By.xpath("//*[#id='ulNotification']/li[5]/h3")).click();
driver.close();
}
It is giving an Exception:
org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 30.16 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.45.0', revision: '5017cb8', time: '2015-02-26 23:59:50'
System info: host: 'BHD22524', ip: '10.11.66.6', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_55'
Session ID: 03f8c7ca-a582-41b5-80d3-2ec53de719f5
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=WINDOWS, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, nativeEvents=false, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=37.0.1}]
At line number 50 i.e.
act.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0, numOfPixels).release().perform();
I tried using try catch, still it is not working.
Thank you in advance.

In for loop condition at number of iteration you are getting exception?
Because once the element is moved or dragged, page DOM will update and that element will not longer available to move again. That's the reason your are getting StaleElementReferenceException. See this explanation about StaleElementReferenceException
And your code to move element should be like below:
act.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0, numOfPixels).release().build().perform();

Related

WebDriver Waits not working on FindElement

WebDriver is not waiting for elements to be enabled or displayed in my web application. The web application extensively uses AJAX/Javascript for loading a very large, dynamic application, specifically Bubble's web application editor (https://bubble.is). I am developing applications using bubble and want to use Selenium/WebDriver from within the Bubble editor.
When using implicit waits, explicit waits and fluent waits, attempts to click on an element always return the following error:
org.openqa.selenium.WebDriverException: unknown error: Element <div class="tab tabs-3">...</div> is not clickable at point (30, 185). Other element would receive the click: <div class="status-notification" style="display: block;">...</div>
This issue appears to be related to elements appearing in the DOM before they are fully loaded. The following Java code is what is being used here, compiled and run in Eclipse IDE on Java 9:
public static void main(String[] args) {
try {
WebDriver chrome = bubbleLogin(false); // login to application via static page. this step works
WebDriver driver = chrome;
// load app
WebDriverWait wait = new WebDriverWait(driver, DEFAULT_TIMEOUT_IN_SECONDS);
driver.get("https://bubble.is/page?type=page&name=index&id=test123456code&tab=tabs-1");
switchToWindowWithTitle("test123456", driver);
// EXPLICIT WAIT: wait for "elementToBeClickable" to be true - element must be displayed and enabled
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.tab.tabs-3")));
// FLUENT WAIT: wait for element.IsEnabled to be true - element must be displayed and enabled
// instantiate an instance of this class to run the wait function I wrote
testng test = new testng();
test.waitUntilElementExistsAndIsEnabled(driver,By.cssSelector("div.tab.tabs-3"));
// only works via sleep... not implicit, explicit or fluent waits
// Thread.sleep(10000);
driver.findElement(By.cssSelector("div.tab.tabs-3")).click();
} catch (Exception e) {
System.out.println("failed run");
e.printStackTrace();
}
}
}
And the above FluentWait method:
private void waitUntilElementExistsAndIsEnabled(WebDriver driver, final By by) {
new FluentWait<WebDriver>(driver).withTimeout(DEFAULT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
.pollingEvery(DEFAULT_SLEEP_TIME_IN_SECONDS, TimeUnit.SECONDS).ignoring(NoSuchElementException.class)
.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wd) {
return wd.findElement(by).isEnabled();
}
});
}
Here is a complete dump of the error message from Eclipse:
(Session info: chrome=61.0.3163.100)
(Driver info: chromedriver=2.32.498537 (cb2f855cbc7b82e20387eaf9a43f6b99b6105061),platform=Mac OS X 10.12.1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'Krystals-MacBook-Air.local', ip: 'fe80:0:0:0:c33:4430:fcfd:933c%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.1', java.version: '9'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=MAC, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=MAC, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.32.498537 (cb2f855cbc7b82e20387eaf9a43f6b99b6105061), userDataDir=/var/folders/gr/lggvp4hn09x2zqg6k561y4fr0000gn/T/.org.chromium.Chromium.haqAAG}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=61.0.3163.100, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]
Session ID: 0c9110334bb1b20a306363006f4bb868
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
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.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:279)
at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:83)
at testng.main(testng.java:497)
i used
thread.sleep before i click the element and then
i will find the parent element before i click the main element
or
(new WebDriverWait(driver, 10)).until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Reset")));
boolean Sort = driver.findElement(By.linkText("Reset")).isDisplayed();
if (Sort == true){
}else{
}
hope it will works

Selenium code for Video click in iFrame works in Debug but fails in normal,tried sleep,wait etc

The code below works as expected in debug mode of Eclipse, but when try Normal mode, I get the error below. I even increased thread.sleep from 3000 to 12000 but still fails at Normal mode.
In debug mode, when I put a breakpoint at line 45 and 46 and step over them, the Video plays.
/**
* Unit test for simple App.
*/
public class AppTest extends TestCase
{
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C://Sprints//chromedriver_win32//chromedriver.exe");
//System.setProperty("webdriver.gecko.driver", "C://Sprints//geckodriver-v0.19.0-win64//geckodriver.exe");
WebDriver driver = new ChromeDriver();
// WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://utubehits.com/");
driver.findElement(By.name("login")).sendKeys("wealthytarundas2015#gmail.com");
driver.findElement(By.name("pass")).sendKeys("Tapan#321");
driver.findElement(By.name("connect")).click();
driver.findElement(By.linkText("YouTube Views")).click();
driver.findElement(By.linkText("Watch Video")).click();
System.out.println(driver.getTitle());
//driver.switchTo().parentFrame();
List<WebElement> frameElements = driver.findElements(By.cssSelector("iframe[id='iframe']"));
//--------- HERE I PUT BREAK POINT ----------
System.out.println(frameElements.size());
//........ HERE I PUT BREAK POINT ----------
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[id='ytPlayer']")));
Thread.sleep(3000);
driver.findElement(By.cssSelector("button[class='ytp-large-play-button ytp-button']")).click();
}
}
Error that appears in the console:
Starting ChromeDriver 2.32.498550 (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a) on port 7753
Only local connections are allowed.
Sep 29, 2017 3:54:25 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
UtubeHits.com - YouTube Exchange Website
1
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"iframe[id='ytPlayer']"}
(Session info: chrome=61.0.3163.100)
(Driver info: chromedriver=2.32.498550 (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a),platform=Windows NT 10.0.15063 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.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'TDAS-PK', ip: '10.239.31.215', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_144'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.32.498550 (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a), userDataDir=C:\Users\prokarma\AppData\Local\Temp\scoped_dir4672_687}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=61.0.3163.100, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]
Session ID: c128094673a6b33419aebb2bbea0e7b6
*** Element info: {Using=css selector, value=iframe[id='ytPlayer']}
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:214)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:356)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:450)
at org.openqa.selenium.By$ByCssSelector.findElement(By.java:430)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)
at basic.basic.AppTest.main(AppTest.java:49)
Thread.sleep(4000);
driver.switchTo().frame("iframe").switchTo().frame("ytPlayer");
driver.findElement(By.cssSelector("button[class='ytp-large-play-button ytp-button']")).click();
Rather than using sleep to wait for the element, try using an explicit WebDriverWait and ExpectedConditions to repeatedly poll the DOM for your desired state.
I've updated your example below:
/**
* Unit test for simple App.
*/
public class AppTest extends TestCase
{
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C://Sprints//chromedriver_win32//chromedriver.exe");
//System.setProperty("webdriver.gecko.driver", "C://Sprints//geckodriver-v0.19.0-win64//geckodriver.exe");
WebDriver driver = new ChromeDriver();
// WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://utubehits.com/");
//This is the magic thing. It will repoll the dom for 25 seconds before it gives up.
WebDriverWait explicitWait = new WebDriverWait(driver, 25);
explicitWait.until(ExpectedConditions.visibilityOfElementLocated(By.name("login"))).sendKeys("wealthytarundas2015#gmail.com");
explicitWait.until(ExpectedConditions.visibilityOfElementLocated(By.name("pass"))).sendKeys("Tapan#321");
explicitWait.until(ExpectedConditions.elementToBeClickable(By.name("connect"))).click();
explicitWait.until(ExpectedConditions.elementToBeClickable(By.linkText("YouTube Views"))).click();
explicitWait.until(ExpectedConditions.elementToBeClickable(By.linkText("Watch Video"))).click();
System.out.println(driver.getTitle());
//driver.switchTo().parentFrame();
List<WebElement> frameElements = explicitWait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("iframe[id='iframe']")));
//--------- HERE I PUT BREAK POINT ----------
System.out.println(frameElements.size());
//........ HERE I PUT BREAK POINT ----------
//I'm not certain I have this exactly right, you may have to fiddle with it a bit
explicitWait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[id='ytPlayer']")));
Thread.sleep(3000);
explicitWait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[class='ytp-large-play-button ytp-button']"))).click();
}
}
Using explicit waits in combination with setting the implicit waits can help to account for many timing conditions various browsers experience during testing.
Best of Luck.

Webdriver Expected condition failed: waiting for element to no longer be visiblr

I have a method which waits for a css (Modal) locator to not be visible on screen, on some of my builds I get the following failed message
Expected condition failed: waiting for element to no longer be
visible: By.cssSelector: .modal-body (tried for 6 second(s) with 500
MILLISECONDS interval)
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'DEV007', ip: '172.16.2.192', os.name: 'Windows Server 2008 R2', os.arch: 'amd64', os.version: '6.1', java.version:
'1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false,
chrome={chromedriverVersion=2.29.461591
(62ebf098771772160f391d75e589dc567915b233),
userDataDir=C:\Users\GI\AppData\Local\Temp\2\scoped_dir7780_13017},
takesHeapSnapshot=true, pageLoadStrategy=normal,
databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false,
version=58.0.3029.110, platform=XP, browserConnectionEnabled=false,
nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true,
webStorageEnabled=true, browserName=chrome, takesScreenshot=true,
javascriptEnabled=true, cssSelectorsEnabled=true,
unexpectedAlertBehaviour=}]
Session ID: eb353964f7b9bd515e527a795a111bc3
My method:
public boolean waitUntilModalDisapears() {
return this.wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".modal-body")));
}
Loading web elements in your page will be different each time you run your code so you should increase the wait time in your web driver wait and try running your code more than once to be sure your driver have waited enough time for the element to be loaded
try below :
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".modal-body")));
There is nothing wrong in this method and you use it right.
The code of this method (on C#) is:
return (Func<IWebDriver, bool>) (driver =>
{
try
{
return !driver.FindElement(locator).Displayed;
}
catch (NoSuchElementException ex)
{
return true;
}
catch (StaleElementReferenceException ex)
{
return true;
}
});
So probably your element was visible indeed. Try to increase your timeout and maybe to make screenshots on failure to be able to view real data and to know if the element is visible or not indeed.

Scroll and click - Not working for both Android and iOS on Appium tool with selenium java

I am trying to scroll and its not working for both Android and iOS, Can you please help me on this.
Look forward to hear back from you.
Did try with ScrollTO and ScrollToExact as both of them are deprecated now, so did try with this:
String str = "CADILLAC";
driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains(\""+str+"\").instance(0))").click();
Still does not work.
Did go through many blogs , videos , course content and material no one has explained or there a specific solution on how to handle this
Did try with below,still gets the error
org.openqa.selenium.WebDriverException:
driver.findElementByAndroidUIAutomator("UiSelector().resourceId(\"current_value_tv\").text(\"All Makes\")").click();
driver.findElementByAndroidUIAutomator("UiSelector().className(\"android.widget.TextView\").text(\"AUSTIN HEALEY\")").click();
org.openqa.selenium.WebDriverException: An unknown server-side error
occurred while processing the command. (WARNING: The server did not
provide any stacktrace information)
Command duration or timeout: 45 milliseconds
Build info: version: '2.45.0', revision: '32a636c', time: '2015-03-05 22:01:35'
System info: host: 'NCA1026471', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version:
'1.8.0_91'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{app=C:\Appium\workspace\Lokesh\app\app-release.apk,
appPackage=au.com.carsguide, rotatable=true,
networkConnectionEnabled=true, noReset=true, warnings={},
handlesAlerts=true, deviceName=Carsguide Product, version=0.17.0,
platform=ANDROID, appActivity=au.com.carsguide.activity.HomeActivity,
desired= {app=C:\Appium\workspace\Lokesh\app\app-release.apk,
appPackage=au.com.carsguide,
appActivity=au.com.carsguide.activity.HomeActivity, noReset=true,
platformVersion=5.0, browserName=, platformName=Android,
deviceName=Carsguide Product, device=Android}, acceptSslCerts=true,
platformVersion=21, automationName=selendroid, browserName=selendroid,
takesScreenshot=true, javascriptEnabled=true, platformName=android,
device=Android}]
Session ID: e90cac4d-38aa-99fd-2dd2-70cc09a0e717
*** Element info: {Using=-android uiautomator, value=UiSelector().resourceId("current_value_tv").text("All Makes")}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method)
you can try this below code, i was trying this code on settings page..
AppiumDriver driver = new AndroidDriver(new URL(""), cap1);
driver.scrollTo("About phone");
Pass the String which is present in the bottom of your app page.
driver.scrollTo("Enter your value");
Use appropriate wait Statements.
use driver.swipe instead of driver.scroll
http://automationbyharsh.blogspot.in/
visit this blog to get full documentation of swipe method for Android and IOS.
scrollTO method is not consistent in appium for android apps. so try the following.
go till model listing page
try the below code snippet , This was for flipkart app
it may help you with your app
driver.findElementById("com.flipkart.android:id/search_autoCompleteTextView").sendKeys("Reebok Shoes" +"\n");
Thread.sleep(8000);
Dimension size = driver.manage().window().getSize();
System.out.println(size);
int Starty=(int)(size.height*0.90);
int Endy=(int)(size.height*0.10);
int Startx=(int)(size.width*0.50);
WebElement ele_item = driver.findElementByClassName("android.widget.TextView");
Thread.sleep(3000);
do
{
List<WebElement> ele_item2 = driver.findElementsByXPath("//*[#index='2'][#text='Reebok SPEED XT Running Shoes'][#class='android.widget.TextView']");
int size2 = ele_item2.size();
System.out.println(size2);
if(size2>0)
{
driver.findElementByXPath("//*[#index='2'][#text='Reebok SPEED XT Running Shoes'][#class='android.widget.TextView']").click();
break;
}
driver.swipe(Startx, Starty, Startx, Endy, 1000);
Thread.sleep(2000);
} while(ele_item.isDisplayed()==true);

org.openqa.selenium.NoSuchElementException - Selenium Test

In Java, I have written a Selenium test for testing Yahoo Movies. I am testing This Movie from yahoo website. But the code that I have written (given below) is throws an Exception (given below). I am new to Selenium, so please solve the problem.
Code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Tests {
WebDriver driver;
Wait<WebDriver> wait;
boolean result;
Tests() {
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 30);
driver.get("http://www.yahoo.com/");
}
public static void main(String arg[]) {
boolean result = new Tests().movies();
System.out.println(result?"PASSED":"FAILED");
}
public boolean movies() {
try {
System.out.print("Testing Movies... ");
driver.findElement(By.linkText("Movies")).click();
driver.findElement(By.linkText("Finding Dory")).click();
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver webDriver) {
return webDriver.findElement(By.className("yvp-flash-video")) != null;
}
});
return driver.findElement(By.id("Main")).getText().contains("'Finding Dory' Trailer");
}
catch(Exception exp) {
exp.printStackTrace();
return false;
}
}
}
Exception:
Testing Movies... org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"Finding Dory"}
Command duration or timeout: 5.08 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40'
System info: host: 'Jahanzeb', ip: '10.99.14.207', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.7.0_79'
*** Element info: {Using=link text, value=Finding Dory}
Session ID: 5f14f1fa-85e4-471e-982f-27317dd766b7
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=WINDOWS, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, nativeEvents=false, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=46.0.1}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByLinkText(RemoteWebDriver.java:428)
at org.openqa.selenium.By$ByLinkText.findElement(By.java:246)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
at Tests.movies(Tests.java:189)
at Main.main(Main.java:14)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"Finding Dory"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40'
System info: host: 'Jahanzeb', ip: '10.99.14.207', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.7.0_79'
Driver info: driver.version: unknown
at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous903980554428331931webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:10770)
at <anonymous class>.FirefoxDriver.prototype.findElement(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous903980554428331931webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:10779)
at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous903980554428331931webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12661)
at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous903980554428331931webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12666)
at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/JAHANZ~1/AppData/Local/Temp/anonymous903980554428331931webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:12608)
FAILED
I am assumming that you are trying to click a "link" named "Finding Dory" on this page:
But this is not a link - try to click it manually, it simply is not possible to click on it.
If you click on it, nothing happens, it's just not clickeable - this is nothing but a simple text "Finding Dory".
What you can do is to click a link named "Play trailer" that is located below the text "Finding Dory". The problem is that there are many links with the same name "Play trailer" on this page, and WebDriver doesn't know which link should be clicked, and returns an error if you try a simple method findElement( By.linkText('Play trailer')).click();
You need to tell WebDriver that it should click on the link that is located under the text "Finding Dory". To do it you need more advanced locating strategies than a simle method By.linkText. The two the most popular are locating using xpath or css expressions.
First you need to examine a structure of this page. Open this page in the browser, and press F12 key - this opens Developer Tools window (how to use this tool is beyond this answer). You will see something like this:
That is:
DIV tag that contains a text "Finding Dory"
followed by A tag that contains a text "Play trailer"
You can build an xpath expression for the above, that finds a link "Play trailer" located under a DIV tag that contains "Finding Dory" in this way :
//div[contains(.,'Finding Dory')]/following-sibling::a[contains(.,'Play trailer')]
and then replace this line of your code:
driver.findElement(By.linkText("Finding Dory")).click();
with this one:
driver.findElement(
By.xpath(
"//div[contains(.,'Finding Dory')]/following-sibling::a[contains(.,'Play trailer')]"
)).click();
You can try the following code
driver.findElement(By.xpath(.//a[contains(text(),'Finding Dory'))].click();
Note: If "Finding Dory" is having any link then only the above code will work.

Categories

Resources