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.
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.
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 read data from a HTML table. The website from where i am trying to read data is gmail Contacts page.
Every-time i run the code i am getting -
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=39.0.2171.99)
(Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 SP1 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 602 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:30'
System info: host: 'Casper-PC', ip: '10.0.0.5', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.8.0_25'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, chrome={userDataDir=C:\Users\Casper\AppData\Local\Temp\scoped_dir7476_21861}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, version=39.0.2171.99, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 1e0f05fdc64ecd5720f0d050a602ee4b
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
at org.openqa.selenium.remote.RemoteWebElement.getText(RemoteWebElement.java:152)
at com.Trial.SortingTable.main(SortingTable.java:36)
Java Code which i have written-
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class SortingTable {
public static void main(String[] agrs) throws InterruptedException{
WebDriver driver = null;
try{
System.setProperty("webdriver.chrome.driver","E:\\chromedriver.exe");
driver= new ChromeDriver();
driver.manage().window().maximize();
//Authentication pop-up
driver.get("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/");
driver.findElement(By.xpath(".//*[#id='Email']")).sendKeys("Gmail Username");
driver.findElement(By.xpath(".//*[#id='Passwd']")).sendKeys("Gmail Password");
driver.findElement(By.xpath(".//*[#id='signIn']")).click();
driver.manage().timeouts().implicitlyWait(14000, TimeUnit.SECONDS);
WebElement wb = driver.findElement(By.xpath(".//*[#id=':j']"));
wb.click();
driver.findElement(By.xpath(".//*[#id=':1h']")).click();
driver.manage().timeouts().implicitlyWait(14000, TimeUnit.SECONDS);
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath(".//*[#id=':16r']/div/div[2]"))).perform();
driver.manage().timeouts().implicitlyWait(14000, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//a[#title='Other Contacts (16)']")).click();
driver.manage().timeouts().implicitlyWait(14000, TimeUnit.SECONDS);
//This is the page which is having the contact
List<WebElement> list = driver.findElements(By.xpath(".//*[#id=':17h']/tbody/tr/td[4]/div"));
for(WebElement lst : list){
//Trying to read the contact
System.out.println(lst.getText());
}//for
}catch(Exception e){
e.printStackTrace();
}//catch
finally{
Thread.sleep(4000);
driver.quit();
System.exit(0);
}//finally
}//main
}//SortingTable
I am trying to read data inside the contacts page but getting this Exception.
This is because of the following two reasons from here:
A stale element reference exception is thrown in one of two cases, the
first being more common than the second:
The element has been deleted entirely. The element is no longer
attached to the DOM.
Generally this happens in ajax based sites. One way is to solve this is to refetch the element, because of ajax call the DOM would have been changed.
Code:
public void Test2() throws Exception{
Thread.sleep(5000);
driver.findElement(By.id("cboMenu")).click();
driver.findElement(By.xpath(".//*[#id='cboMenu/option[3]")).click();
}
Error:
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"cboMenu"}
Command duration or timeout: 31 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:03'
System info: host: 'venu-PC', ip: '192.168.1.3', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_51'
Session ID: 0f859bed-35df-4eba-a472-3bc2efec4814
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Please use explicit wait instead of the Thread.sleep(5000), like in the next example.
It will provide you much clearer error regarding what you experience.
public void Test2() throws Exception{
new WebDriverWait(driver, 3).until(ExpectedConditions.visibilityOfElementLocated(By.id("cboMenu")))
driver.findElement(By.id("cboMenu")).click();
driver.findElement(By.xpath(".//*[#id='cboMenu/option[3]")).click();
}
Next, verify your button doesn't appear in different iFrame. If you do, change the iFrame to the one you element inside:
driver.switchTo().frame("IFRAME_ID");
The IFRAME_ID is taken from the DOM:
<iframe id="IFRAME_ID">
You can next change visibilityOfElementLocated to presenceOfElementLocated, that will verify that an element is present on the DOM but does not necessarily mean that the element is visible. It can be good clue to know if your webDriver is in the correct scope with the button you try to click.
Additional tip - scroll the button you want to click on into view. Thats could be also the reason to failure.
//element is WebElement
(JavascriptExecutor)driver.executeScript("arguments[0].scrollIntoView(true);", element);
this is solved my issue :)
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.context("WEBVIEW_com.openstream.cueme.services.workbench");
Thread.sleep(10000);
driver.findElementById("userId").sendKeys("sysadmin");
driver.findElementById("CuemePassword").sendKeys("MMNext13#");
Try below code
public void Test2() throws Exception{
Thread.sleep(5000);
driver.findElement(By.id("cboMenu")).click();
driver.findElement(By.xpath(".//*[#id='cboMenu']/option[3]")).click();