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();
Related
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
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.
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.
I am trying to use WebElement#getScreenShotAs(OutputType.FILE) feature added in selenium webdriver 2.47.0 version on Firefox Browser
Code
public static void main(String[] args) throws IOException {
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://automationpractice.com/index.php");
WebElement element=driver.findElement(By.cssSelector("a[title='Contact Us']"));
System.out.println(element.getText());
element.getScreenshotAs(OutputType.FILE);
File destination=new File("Image.png");
FileUtils.copyFile(null, destination);
}
..But I am getting below exception:
Contact us
Exception in thread "main" org.openqa.selenium.UnsupportedCommandException: Unrecognized command: GET /session/e796089b-1d64-4590-9157-a0716a57e399/screenshot/%7B4329461b-5e9c-4f8b-b589-ddc1af1d55a6%7D
Command duration or timeout: 16 milliseconds
Build info: version: '2.52.0', revision: '4c2593cfc3689a7fcd7be52549167e5ccc93ad28', time: '2016-02-11 11:22:43'
System info: host: 'mrunal-laptop', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_45'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=41.0.2, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: e796089b-1d64-4590-9157-a0716a57e399
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:422)
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.RemoteWebElement.execute(RemoteWebElement.java:327)
at org.openqa.selenium.remote.RemoteWebElement.getScreenshotAs(RemoteWebElement.java:447)
at thirdsession.GetProperties.main(GetProperties.java:20)
The real reason for the error is that many / most WebDriver implementations do not actually support element-based screenshots, despite WebElement extending TakesScreenshot since 2.47.0. Perhaps someday this will change.
If you want screenshots you need to do them at the whole-browser level, in which case - as other answers have it - you need to pass the WebDriver instance.
File ssFile = ((TakesScreenshot)(driver)).getScreenshotAs(OutputType.FILE);
Strictly speaking you should probably do the following, since not all Drivers are guaranteed to support screenshots, e.g. HtmlUnitDriver.
if (!(getDriver() instanceof TakesScreenshot)) {
File ssFile = ((TakesScreenshot)(driver)).getScreenshotAs(OutputType.FILE);
// ...
}
There are alternate solutions for single-element screenshots, but they inevitably involve cropping of the full-browser screenshot. See, for example: https://stackoverflow.com/a/13834607/954442
Update: just to clarify that this is not a bug, it's that although element screenshots are a part of the W3C WebDriver spec, different browsers have different levels of compliance/coverage, and as far as I know this feature is only supported by Microsoft Edge.
Dont Import these lib from Suggestions,
import org.eclipse.jetty.server.Response.OutputType;
import org.seleniumhq.jetty9.server.Response.OutputType;
Import these lib.
import org.openqa.selenium.OutputType;
It should be something like this.
File screenS = ((TakesScreenshot)(driver)).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenS, new File("C:\\akshay\\del\\screenshots\\1.jpg"));
replace the above code with
element.getScreenshotAs(OutputType.FILE);
File destination=new File("Image.png");
FileUtils.copyFile(null, destination);
The getScreenShotAs() method is not defined as part of the WebElement interface. Rather, it is included as part of the TakesScreenshot interface. If you want to take a screenshot and save it to a file, try the following:
File file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
I am trying to use WebDriver to automate an website.
I am using Firefox Driver, but the homepage has a Pop-up modal alert window: saying:
You need to use IE 6.0 for viewing this application. Else some
features may not work
I checked the Source of the page, it has a function.
The Modal Alert is not an HTML element, I tried finding any element with FireBug, but to no avail.
if ( strBrowName == "Microsoft Internet Explorer" )
{
if ( (( strBrowVersion.indexOf( 'MSIE 6' ) ) > 0 ) )
{
}
else
{
alert( "You need to use IE 6.0 for viewing this application. Else some features may not work" );
}
In my WebDriver code I am using the following capability in the Driver (as suggested by some other post here)
DesiredCapabilities dc=new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR,UnexpectedAlertBehaviour.ACCEPT);
WebDriver driver =new FirefoxDriver(dc);
Then I am making a simple get call, enclosed in a try-catch:
try {
driver.get(B);
}
catch (UnhandledAlertException e) {
System.err.println("Caught UnhandledAlertException: ");
}
System.out.println("URL Opened");
If I do not write any method on the driver object and close the driver instead.
The program terminates in Eclipse normally, but the Modal Alert stays open, inspite of the:
UnexpectedAlertBehaviour.ACCEPT
But, if I use ANY driver related method or operation, like, as simple as getTitle:
String title = driver.getTitle();
The Java code fails with Exception, BUT the modal Alert pop-up closes!
And the last line number of the error is given as the line where I used
the first driver related operation.
Please share your thoughts...
Exception in thread "main" org.openqa.selenium.UnhandledAlertException: Unexpected modal dialog (text: You need to use IE 6.0 for viewing this application. Else some features may not work): You need to use IE 6.0 for viewing this application. Else some features may not work
Build info: version: '2.46.0', revision: '87c69e2', time: '2015-06-04 16:17:10'
System info: host: 'LFY2DSY1', ip: '30.142.106.199', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_25'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=38.0.5, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: a97ab146-4929-4502-98f2-810169cc5532
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.createUnhandledAlertException(ErrorHandler.java:185)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:152)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:605)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:628)
at org.openqa.selenium.remote.RemoteWebDriver.getTitle(RemoteWebDriver.java:319)
at SelPkg.CIRS.main(CIRS.java:76)
The behaviour is intended. Here is how it works -
You issue driver.get(B). It triggers the browser to open the webpage and then it doesnt have anything to do with the browser, so it doesnt care whether an alert is open or not.
When the page loads, pop-up dialog appears, but nothing happens on your code side or Eclipse.
When you try to perform another operation, it interacts with browser and sees an unexpected popup dialog.
Now, the problem occurs that modal dialog closes and still exception occurs, so try the following.
Enclose your second operation in a try/catch and handle UnhandledAlertException
Inside that catch block, perform, driver -> switch to -> alert -> accept
After the catch block, perform the second operation again.