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.
Related
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();
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);
My problem is I have 3 defined iFrames on the page I am trying to work on. They are all named the following:
<iframe class="col-51" height="560" src="https://attendee.gototraining.com/embed/886b2/catalog/40xxxx bgColor=ffffff" frameborder="0"></iframe>
<iframe class="col-51" height="560" src="https://attendee.gototraining.com/embed/886b2/catalog/37xxxx bgColor=ffffff" frameborder="0"></iframe>
<iframe class="col-51" height="560" src="https://attendee.gototraining.com/embed/886b2/catalog/46xxxx bgColor=ffffff" frameborder="0"></iframe>
I have tried to driver.switchTo.frame command but it only sees index 0 which I assume is the first frame listed here. If I select this first frame I don't get an error at runtime, however I still cannot see any elements inside the frame. I get "cannot find element" issue. I cant even select the 2nd or 3rd frame with switchTo using either a located I make or index 1 or 2.
I have also tried making a List involving all tagnames of iframe. I get back only 1 result. Again, I see 3 here. And again, even when I choose the first one I still cannot see any elements inside the frame using conventional means.
What am I missing here?
Also please note I have put x's in for the pathway because of privacy concerns.
Here is a capture of what happens if I choose another index other than 0:
org.openqa.selenium.NoSuchFrameException: Unable to locate frame: 1
Command duration or timeout: 62 milliseconds
Build info: version: '2.52.0', revision: '4c2593c', time: '2016-02-11 19:03:33'
System info: host: 'DESKTOP-1PV0EPA', ip: '192.168.0.11', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_77'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=46.0.1, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
You can use xpath locator and identify a frame by partial src link:
void switchToIframe(int catalogId)
{
driver.switchTo().defaultContent(); // don't get trapped in iframes
driver.switchTo().frame(
driver.findElement(
By.xpath("//iframe[contains(#src, 'catalog/" + catalogId + "')]"));
}
use it like:
switchToIframe(40); // frame 1
switchToIframe(36); // frame 2
switchToIframe(46); // frame 3
you may also need to wait for frames to load before switching to them
I would suggest trying to resolve the iframes as WebElements by their XPaths. Code snippet below stubs out the test case, you'll need to determine the xpaths to each of your iframes and fill the strings in, but I think this should be close.
private static final By FRAME_PATH_1 = By.xpath("");
private static final By FRAME_PATH_2 = By.xpath("");
private static final By FRAME_PATH_3 = By.xpath("");
private void traverseFrames(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement frame1 = wait.until(ExpectedConditions.presenceOfElementLocated(FRAME_PATH_1));
WebElement frame2 = wait.until(ExpectedConditions.presenceOfElementLocated(FRAME_PATH_2));
WebElement frame3 = wait.until(ExpectedConditions.presenceOfElementLocated(FRAME_PATH_3));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frame1));
System.out.println("in Frame 1");
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frame2));
System.out.println("in Frame 2");
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frame3));
System.out.println("in Frame 3");
}
XPaths are not great for maintainability if you expect the page contents to change, but it may get you closer to what you're looking for. I use the Firepath extension for Firebug to help resolve xpaths.
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 facing an Issue wherein I get an Exception saying UnhandledAlertException Modal Dialog Present ,below are some of the traces
org.openqa.selenium.UnhandledAlertException: Modal dialog present:
This page is asking you to confirm that you want to leave - data you
have entered may not be saved.Build info: version: '2.41.0', revision:
'3192d8a6c4449dc285928ba024779344f5423c58', time: '2014-03-27
11:29:39'System info: host: 'NCESEPBLRNRE16', ip: '172.16.137.213',
os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1',
java.version: '1.6.0_26'Session ID:
bda22089-a586-4cd8-b7ac-778c98581e11Driver info:
org.openqa.selenium.firefox.FirefoxDriverCapabilities [{platform=XP,
acceptSslCerts=true, javascriptEnabled=true, browserName=firefox,
rotatable=false, locationContextEnabled=true, version=23.0,
cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true,
browserConnectionEnabled=true, nativeEvents=false,
webStorageEnabled=true, applicationCacheEnabled=true,
takesScreenshot=true}] at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at
org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
at
org.openqa.selenium.remote.ErrorHandler.createUnhandledAlertException(ErrorHandler.java:174)
at
org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:141)
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:214) at
org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:340)
at
com.amadeus.selenium.runner.SEPWebDriverWrapper.findElement(SEPWebDriverWrapper.java:141)
I searched for some solutions and got the following snippet to handled the issue
//Now the alert appears. Alert alert = driver.switchTo().alert();
alert.accept();
It works fine , but the alert popup appears in different instances (or different scenarios ) for which the alert cannot be handled in all blocks of code
Please let me know if there is any common approach wherein i can disable this alert popup permanently through some firefox profile settings or anyother generic approaches
I am using Selenium Java with browser as Firefox
Write a method like this:
protected boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
Call the above method to verify whether alert is present or not as below:
if(isAlertPresent()){
System.out.println(isAlertPresent());
driver.switchTo().alert().accept();
}
This can be solved using combination of Robot class and selenium Alert switch to command.
driver.switchTo().alert();
// invoke Robot class
Robot rb = new Robot();
rb.KeyPress(KeyEvent.VK_ENTER);
rb.KeyPress(KeyRelease.VK_ENTER);
try this out and let me know if any issues. it worked for me because I have faced thi issue earlier.