If any one logged inside any application using chrome browser,notification pop-up appears to save password/Allow notification.
How to handle this notification pop-up through selenium web-driver? Sometimes two pop-ups appears(one is for save password and another one is to allow notification).I have already tried to handle using Alert class but could not succeeded.kindly help me on this.
You can open use ChromeOptions Class. Below is the sample code.
ChromeOptions chrome_Profile = new ChromeOptions();
chrome_Profile.addArguments("chrome.switches","--disable-extensions");
chrome_Profile.addArguments("--disable-save-password");
chrome_Profile.addArguments("disable-infobars");
System.setProperty("webdriver.chrome.driver","c/chromedriver.exe");
//Passing chrome_Profile while initializing the ChromeDriver
WebDriver driver = new ChromeDriver(chrome_Profile);
Let me know if this helps.
You can use below code to allow chrome to send notifications:
ChromeOptions options=new ChromeOptions();
Map<String, Object> prefs=new HashMap<String,Object>();
prefs.put("profile.default_content_setting_values.notifications", 1);
//1-Allow, 2-Block, 0-default
options.setExperimentalOption("prefs",prefs);
ChromeDriver driver=new ChromeDriver(options);
#Pritesh patel
it didnt work for me.. I want to allow the flash to run
package com.selenium.Basics;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
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.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import Flash.FlashObjectWebDriver;
public class GuruPgm14FlashTesting {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String driverPath="C:\\selenium\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", driverPath);
ChromeOptions options=new ChromeOptions();
Map<String, Object> prefs=new HashMap<String,Object>();
prefs.put("profile.default_content_setting_values.notifications", 1);
//1-Allow, 2-Block, 0-default
options.setExperimentalOption("prefs",prefs);
WebDriver driver=new ChromeDriver(options);
driver.get("http://demo.guru99.com/test/flash-testing.html");
Thread.sleep(5000);
driver.findElement(By.xpath("//embed[#play='false']")).click();
System.out.println("Clicked to allow the addon");
Thread.sleep(5000);
FlashObjectWebDriver fdriver= new FlashObjectWebDriver(driver, "myFlashVideo");
fdriver.callFlashObject("Play");
Thread.sleep(5000);
fdriver.callFlashObject("StopPlay");
Thread.sleep(5000);
fdriver.callFlashObject("SetVariable","/:message","Flash testing using selenium Webdriver");
System.out.println(fdriver.callFlashObject("GetVariable","/:message"));
}
}
const webdriver = require('selenium-webdriver');
var chromeCapabilities = webdriver.Capabilities.chrome();
var chromeOptions = {
'args': ['--disable-notifications']
};
chromeCapabilities.set('chromeOptions', chromeOptions);
If you are using js. Especially when website adding now option to provide add on your screen or even the www dot come want to send you notification, this ultimately makes your windows blackened and inaccessible to element in it.
Try to put this on a different JS file if u do. Cause export is a function
in Python:
if browser == "chrome":
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)
self.driver = webdriver.Chrome(chrome_options=chrome_options)
self.driver.maximize_window()
self.driver.implicitly_wait(10)
You can use ChromeOptions class to allow / disable notification popup.
Please find code below :
Map<String, Object> prefs = new HashMap<String, Object>();
// 1 for allowing, 2 for disabling popup
prefs.put("profile.default_content_setting_values.notifications", 1);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
We can disable all type chrome notifications such as save password, allow locations..., just by adding only one argument.
ChromeOptions ops = new ChromeOptions();
ops.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", ""c/chromedriver.exe"");
WebDriver driver = new ChromeDriver(ops);
hope this helps you.
Thanks.
Related
Capture browser network logs running in Saucelabs.
I used following code to catpuring browser network logs running in Saucelabs.
Its working in local machine, able to capture logs in local, but not able capture when running in saucelabs.
Here is the code. can anybody please though some light on this?
++++++++++ Local working fine +++++++++
package automation.networklogs;
import net.lightbody.bmp.BrowserMobProxy;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.client.ClientUtil;
import net.lightbody.bmp.core.har.Har;
import net.lightbody.bmp.proxy.CaptureType;
import org.openqa.selenium.By;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
public class NetWorkLogsWithMobProxyLocal {
public static String sFileName = "C:/Users/DELL/Desktop/New folder/harfile2.har";
public static WebDriver driver;
public static BrowserMobProxy proxy;
public static void main(String[] args) throws InterruptedException, MalformedURLException {
try {
proxy = new BrowserMobProxyServer();
proxy.start(0);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
try {
String hostIp = Inet4Address.getLocalHost().getHostAddress();
seleniumProxy.setHttpProxy(hostIp + ":" + proxy.getPort());
seleniumProxy.setSslProxy(hostIp + ":" + proxy.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
}
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
System.setProperty("webdriver.chrome.driver", "C:/Users/DELL/IdeaProjects/prodigy-client-repo/zenq/src/test/resources/browser_drivers/chromedriver.exe" );
ChromeOptions options = new ChromeOptions();
options.merge(capabilities);
driver = new ChromeDriver(options);
driver.manage().window().maximize();
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
proxy.newHar("yahoo.com" );
driver.get("https://yahoo.com" );
Thread.sleep(10);
Har har = proxy.getHar();
File harFile = new File(sFileName);
try {
har.writeTo(harFile);
} catch (IOException ex) {
System.out.println(ex.toString());
System.out.println("Could not find file " + sFileName);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("ENTER IN EXCEPTION firstName" );
} finally {
if (driver != null) {
proxy.stop();
driver.quit();
}
}
}
}
+++++++++ ++++++++++ saucelabs not working +++++++++
package automation.networklogs;
import net.lightbody.bmp.BrowserMobProxy;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.client.ClientUtil;
import net.lightbody.bmp.core.har.Har;
import net.lightbody.bmp.proxy.CaptureType;
import org.openqa.selenium.By;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
public class NetWorkLogsWithMobProxySL {
public static String sFileName = "C:/Users/DELL/Desktop/New folder/harfile3.har";
public static WebDriver driver;
public static BrowserMobProxy proxy;
public static void main(String[] args) throws InterruptedException, MalformedURLException {
try {
proxy = new BrowserMobProxyServer();
proxy.start(0);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
String hostIp = Inet4Address.getLocalHost().getHostAddress();
seleniumProxy.setHttpProxy(hostIp + ":" + proxy.getPort());
seleniumProxy.setSslProxy(hostIp + ":" + proxy.getPort());
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
MutableCapabilities sauceOpts = new MutableCapabilities();
sauceOpts.setCapability("username", "username" );
sauceOpts.setCapability("accessKey", "acceskey" );
sauceOpts.setCapability("seleniumVersion", "3.141.59" );
sauceOpts.setCapability("name", "test" );
sauceOpts.setCapability("proxy", hostIp+":"+proxy.getPort() );
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("browser.visible", true);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.merge(capabilities);
MutableCapabilities cap = new MutableCapabilities();
cap.setCapability("sauce:options", sauceOpts);
cap.setCapability("goog:chromeOptions", options);
cap.setCapability("platformName", "Windows 10" );
cap.setCapability("browserName", "chrome" );
cap.setCapability("browserVersion", "latest" );
String sauceURL = "https://ondemand.saucelabs.com:443/wd/hub";
driver = new RemoteWebDriver(new URL(sauceURL), cap);
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
proxy.newHar("yahoo.com" );
driver.get("https://yahoo.com" );
Thread.sleep(10);
Har har = proxy.getHar();
File harFile = new File(sFileName);
try {
har.writeTo(harFile);
} catch (IOException ex) {
System.out.println(ex.toString());
System.out.println("Could not find file " + sFileName);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("ENTER IN EXCEPTION firstName" );
} finally {
if (driver != null) {
proxy.stop();
driver.quit();
}
}
}
}
+++++++++ got below error for running in Saucelabs
log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Sep 17, 2020 12:20:09 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
org.openqa.selenium.WebDriverException: unknown error: net::ERR_PROXY_CONNECTION_FAILED
(Session info: chrome=85.0.4183.83)
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'RAVILAPTOP', ip: '192.168.147.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_77'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities [{networkConnectionEnabled=false, chrome={chromedriverVersion=85.0.4183.38 (9047dbc2c693f044042bbec5c91401c708c7c26a-refs/branch-heads/4183#{#779}), userDataDir=C:\Users\ADMINI~1\AppData\Local\Temp\scoped_dir2300_1366152112}, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, unhandledPromptBehavior=dismiss and notify, strictFileInteractability=false, platform=WINDOWS, proxy=Proxy(manual, http=192.168.147.1:59693, ssl=192.168.147.1:59693), goog:chromeOptions={debuggerAddress=localhost:49770}, browserVersion=85.0.4183.83, acceptInsecureCerts=false, browserName=chrome, javascriptEnabled=true, platformName=WINDOWS, setWindowRect=true, webauthn:virtualAuthenticators=true}]
Session ID: ebf16fbb5f7a4f5d8a91755b8a0966f9
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.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:185)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:120)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:310)
at automation.networklogs.NetWorkLogsWithMobProxySL.main(NetWorkLogsWithMobProxySL.java:77)
You're getting org.openqa.selenium.WebDriverException: unknown error: net::ERR_PROXY_CONNECTION_FAILED because BrowserMob Proxy is running on your local machine, and is completely inaccessible from the Sauce Labs browser.
Normally, to access local-only resources during a test on Sauce Labs, you'd use Sauce Connect. That won't work here, because Sauce Connect is itself configured as a system proxy for the browser under test. If you configure a different proxy using Selenium's proxy settings, Sauce Connect will no longer work.
You can do one of two things. The complicated solution is to set up Sauce Connect, and configure it so that the client you run on your machine uses BrowserMob Proxy. There's some documentation on here.
The second, and much easier solution, is to use extended debugging. Then, Sauce Labs'll automatically capture the HAR file for you, along with JS Console logging. As long as the platform you're testing with supports it, you'll just have to add the desired capability extendedDebugging and set it to true. After a test is finished, you can download the HAR file from the REST API or Web UI.
(If you're using BrowserMob Proxy to alter requests as they come through, then you might find extended debugging's traffic editing useful... Although I personally recommend avoiding this kind of fiddling in tests as much as possible.)
I want to download a file in Selenium web driver in C#.
i have the url in the web element as the attribute href. With that url, i have to download the file through javascript executor.
I tried with js executescript to get the file in the form of bytes and then converting it to pdf file and storing in my desired location. But no luck
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.win-rar.com/predownload.html?&L=0");
string linkVal = driver.FindElement(By.LinkText("Download WinRAR")).GetAttribute("href");
var href = "https://www.win-rar.com/fileadmin/winrar-versions/winrar/winrar-x64-571.exe";
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
/// Object reposne = js.ExecuteScript("arguments[0].setAttribute(arguments[1],arguments[2])", linkVal, "href", "https://www.win-rar.com/postdownload.html?&L=0");
String script = "document.querySelector('a[href*=\"/print/\"]').setAttribute('download','name-of-the-download-file-recommend-guid-or-timestamp.pdf');";
///Object reposne = js.ExecuteAsyncScript(script , href);
var bytes = Convert.FromBase64String(reposne.ToString());
File.WriteAllBytes("F:\\file.exe", bytes);
I'm actually using RestSharp.
Like so:
public FileInfo DownloadFile(string downloadUrl)
{
RestClient rest = new RestClient();
RestRequest request = new RestRequest(downloadUrl);
byte[] downloadedfile = rest.DownloadData(request);
string tempFilePath = Path.GetTempFileName();
File.WriteAllBytes(tempFilePath, downloadedfile);
return new FileInfo(tempFilePath);
}
Consider not creating a rest client for each download request.
The RestClient also supports a base URL for convenience.
Hope this is what you wanted.
I have tested your scenario using Java, Selenium and TestNG. Where you can save the file in the root folder directory
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class FileDownload {
File folder;
WebDriver driver;
#SuppressWarnings("deprecation")
#BeforeMethod
public void setUp() {
//a random folder will be created 88998-98565-09792-783727-826233
folder = new File(UUID.randomUUID().toString());
folder.mkdir();
//Chrome Driver
System.setProperty("webdriver.chrome.driver", "---Your Chrome Driver or chromedriver.exe URL;--");
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
//When you click on download, it will ignore the popups
prefs.put("profile.default_content_settings.popups", 0);
prefs.put("download.default_directory", folder.getAbsolutePath());
options.setExperimentalOption("prefs", prefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(cap);
}
#Test
public void downloadFileTest() throws InterruptedException{
driver.get("https://www.win-rar.com/predownload.html?&L=0");
driver.findElement(By.linkText("Download WinRAR")).click();
/* Depending on your download speed you have to increase or decrease the sleep value, if you give less than download time it will give error as: java.lang.AssertionError: expected [true] but found [false] */
Thread.sleep(5000);
File listOfFiles[] = folder.listFiles();
Assert.assertTrue(listOfFiles.length>0);
for(File file: listOfFiles){
Assert.assertTrue(file.length()>0);
}
}
#AfterMethod
public void tearDown() {
driver.quit();
/* You can comment below "for loop": for testing purpose where you can see the folder and file download, if you uncomment it will delete the file and folder: useful for regression you wont end up having so many files in the root folder */
for(File file: folder.listFiles()){
file.delete();
}
folder.delete();
}
}
If you are just trying to download the file, all you really need is this.
driver.FindElement(By.Id("download-button")).Click();
This will save it in your default location for your browser.
or in js executor
WebElement element = driver.findElement(By.id("download-button"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
To go to a specific location, try adding chrome options:
in C#
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArguments("disable-infobars");
options.AddUserProfilePreference("download.default_directory", "My Path");
options.AddUserProfilePreference("profile.password_manager_enabled", false);
options.AddUserProfilePreference("credentials_enable_service", false);
_Driver = new ChromeDriver(#"DriverPath"), options);
_wait = new WebDriverWait(_webDriver, TimeSpan.FromSeconds(10));
_Driver.Manage().Window.Maximize();
as a last resort, just move the file with:
public class MoveMyFile
{
static void Main()
{
string sourceFile = #"C:\My\File\Path\file.txt";
string destinationFile = #"C:\My\New\Path\file.txt";
// Move my file to a new home!
System.IO.File.Move(sourceFile, destinationFile);
}
}
I am using nCino application (build on Salesforce) for my project. nCino is a framework built on Salesforce application and called in a .
I am trying to automate functional flows in nCino UI through Selenium Java in Chrome browser (tried in Firefox too)
Issue 1: Switch to iframe and click on element
Refer to iframe code below
Console error:
Selenium Code Snippet to switch to iframe and click element inside element:
package nCInoAutomation;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.http.Header;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.html5.ApplicationCache;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Main {
public static void main(String args[]) throws InterruptedException {
//System.setProperty("webdriver.gecko.driver", Parameters.FIREDRIVER);
System.setProperty("webdriver.chrome.driver", Parameters.CHROMEDRIVER);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
// chromeOptions.addArguments("--disable-web-security");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//WebDriver driver = new FirefoxDriver();
driver.get(Parameters.APPURL);
Thread.sleep(2000);
WebElement formElement = driver.findElement(By.id("login_form"));
formElement.findElement(By.id(Parameters.UNAME_XPATH)).sendKeys(Parameters.UNAME);
formElement.findElement(By.id(Parameters.PWD_XPATH)).sendKeys(Parameters.PWD);
formElement.findElement(By.id(Parameters.ENTER_XPATH)).sendKeys(Keys.ENTER);
Thread.sleep(20000);
System.out.println("Wait Over");
WebDriverWait wait=new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(2));
List<WebElement> list = driver.findElements(By.tagName("iframe"));
System.out.println(list.size());
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement ele = list.get(2);
js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", ele);
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,500)", "");
System.out.println("********Switched to the iframe*******");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#id='ncSecondaryNavigation']//span[text()='Loan'])[2]")));
System.out.println("Clicked");
}
}
It says that it has switched to iframe but doesnt look like so.
Issue 2: Unable to locate element
Also, iframe contains most of the angular js elements hence Unable to identify elements. See screenshot below:
Application looks somewhat like below:
Can you please help me automate below:
1. Switch to iframe once landed on Salesforcw screen.
2. Navigate to 'Collateral' screen by clicking on the link.
I have Home Page, from the if I click Login, it will be navigated to another page (there i have to enter login credentials to login the account.
Without the below piece of Code, it is perfectly working for Firefox and Chrome.. But IE it is not working.. I assumed to add wait so that IE problem will resolve..
WebDriverWait Test_Wait=new WebDriverWait(driver,10);
WebElement click=Test_Wait.until(ExpectedConditions.elementIfVisible("login_xpath"));
I have added this code.. But I am getting error to change elementIfVisible to elementClickable.. If i change to elementClickable. Again it is giving error to change elementIfVisible.. How to resolve this??
package com.test.testCase;
import java.io.File;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.test.utitlity.clickEvent;
import com.test.utitlity.globalVariables;
import com.test.utitlity.switchWindow;
public class driverManager extends globalVariables{
public static void driverManager(){
browser="ie";
if(browser.equals("ie")){
File file = new File("./IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getPath());
driver= new InternetExplorerDriver();
}
else if (browser.equals("firefox"))
{
driver=new FirefoxDriver();
}
else if (browser.equals("chrome"))
{
File file= new File("./chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getPath());
System.out.println(file.getPath());
driver=new ChromeDriver();
}
driver.get("http://www.xxxx.in");
clickEvent.clickAt("login_xpath");
WebDriverWait Test_Wait=new WebDriverWait(driver,10);
WebElement click=Test_Wait.until(ExpectedConditions.elementIfVisible("login_xpath"));
switchWindow.swindow("TST.");
}
}
From the code as I can see, you are using it incorrectly. First, you have to wait for the element to be visible and then you have to click on it but you are using it the other way around, and hence it is not able to find the login button as it has been clicked and you are in the new page already.
Please use the wait like this. This will work in all browsers (IE, always a hindrance, but it will work nevertheless):
try{
WebDriverWait Test_Wait=new WebDriverWait(driver,20);
WebElement click=Test_Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("login_xpath")));
clickEvent.clickAt("login_xpath");
}catch(Throwable e){
System.err.println("The login element is not found");
}
I cannot get any automation working with Appium vs the Safari mobile browser on an iOS emulator. In my Java project, Safari will launch, but the browser will not even navigate to the specified website. Can anyone tell me what I'm doing wrong with my code?
1) Launch the Appium application on my OSX machine. It is configured with the following settings:
IP Address: 127.0.0.1
Port: 4723
Force Device: Checked - iPhone
User Mobile Safari: Checked
(Note: No messages scroll across the Appium application log screen when I run my project. Previously, I got complaints about a missing iOS 6.0 library, but when I duplicated the 6.1 iOS library and then renamed the directory to 6.0, the messages went away.)
2) Launch Eclipse and open Appium Project
3) Right-click on test code and click RunAs Junit
4) The iPhone emulator launches -- iPhone iOS 6.1
5) Mobile Safari launches...and then goes nowhere (should be going to cnn.com). I get no errors.
Can Appium Java projects actually be used for mobile-Safari automation? I don't see any examples of Safari automation in the Appium sample code repo.
What gives?
Thanks,
Larry
------------------Java code below----------------------------------------
Eclipse Juno is being used to run my Java/Appium project. Here is a much simplified listing of the Java JUnit project code (which, when modified accordingly, and used with iWebDriver and the deprecated iPhoneDriver(), works fine):
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class AppiumiPhoneWebDriverDemo {
private String baseUrl;
private WebDriver driver;
#Before
public void setup() throws Exception
{
WebDriver driver;
DesiredCapabilities cap = new DesiredCapabilities();
//cap.setCapability("", "");
//cap.setCapability("browsername", "");
//cap.setCapability("os", "iOS 6.1");
cap.setCapability("device", "iPhone Simulator");
cap.setCapability("app", "safari");
driver = new RemoteWebDriver(new URL("http://localhost:4723/wd/hub"), cap);
baseUrl = "http://www.cnn.com";
}
#After
public void tearDown() throws Exception
{
driver.quit();
}
#Test
public void test_searchWorks() throws Exception
{
this.driver.get(baseUrl);
driver.quit();
}
}
You can definitely do this.
See this code
"use strict";
require("./helpers/setup");
var wd = require("wd"),
_ = require('underscore'),
serverConfigs = require('./helpers/appium-servers');
describe("ios safari", function () {
this.timeout(300000);
var driver;
var allPassed = true;
before(function () {
var serverConfig = process.env.SAUCE ?
serverConfigs.sauce : serverConfigs.local;
driver = wd.promiseChainRemote(serverConfig);
require("./helpers/logging").configure(driver);
var desired = _.clone(require("./helpers/caps").ios81);
desired.browserName = 'safari';
if (process.env.SAUCE) {
desired.name = 'ios - safari';
desired.tags = ['sample'];
}
return driver.init(desired);
});
after(function () {
return driver
.quit()
.finally(function () {
if (process.env.SAUCE) {
return driver.sauceJobStatus(allPassed);
}
});
});
afterEach(function () {
allPassed = allPassed && this.currentTest.state === 'passed';
});
it("should get the url", function () {
return driver
.get('https://www.google.com')
.sleep(1000)
.waitForElementByName('q', 5000)
.sendKeys('sauce labs')
.sendKeys(wd.SPECIAL_KEYS.Return)
.sleep(1000)
.title().should.eventually.include('sauce labs');
});
it("should delete cookie passing domain and path", function () {
var complexCookieDelete = function(name, path, domain) {
return function() {
path = path || '|';
return driver.setCookie({name: name, value: '', path: path,
domain: domain, expiry: 0});
};
};
return driver
.get('http://en.wikipedia.org')
.waitForElementByCss('.mediawiki', 5000)
.allCookies() // 'GeoIP' cookie is there
.deleteCookie('GeoIP')
.allCookies() // 'GeoIP' is still there, because it is set on
// the .wikipedia.org domain
.then(complexCookieDelete('GeoIP', '/', '.wikipedia.org'))
.allCookies() // now 'GeoIP' cookie is gone
.sleep(1000);
});
});
Why do you define a second WebDriver in your setUp method ? Remove this second definition to set up the class member driver.
DesiredCapabilities cap = new DesiredCapabilities();
//cap.setCapability("", "");
//cap.setCapability("browsername", "");
//cap.setCapability("os", "iOS 6.1");
cap.setCapability("device", "iPhone Simulator");
cap.setCapability("app", "safari");
should be
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("deviceName", "iPhone Simulator");
cap.setCapability("browsername", "safari");
cap.setCapability("platformVersion", "7.1");
cap.setCapability("platformName", "iOS");
It works for me. hope it fix your issue. Good luck.
Assuming you're using Java on Mac, here's something which works for me, including the code to start Appium Service itself, then the driver to connect to it:
package baseTest;
import com.groupon.tests.mainapp.pages.*;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class AppiumSafariBaseUITest {
private WebDriver wd;
protected WebDriver getDriver(){
return wd;
}
String nodePath = "/Applications/Appium.app/Contents/Resources/node/bin/node";
String appiumJSPath = "/usr/local/lib/node_modules/appium/build/lib/main.js";
AppiumDriverLocalService service;
String service_url;
private void startAppiumServer() throws IOException {
service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
.usingPort(4890)
.usingDriverExecutable(new File(nodePath))
.withAppiumJS(new File(appiumJSPath))
);
service.start();
}
#BeforeClass(alwaysRun = true)
public void setUpAppiumDriver() throws IOException {
startAppiumServer();
service_url = service.getUrl().toString();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("appium-version", "1.0");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("platformVersion", "9.3");
capabilities.setCapability("deviceName", "iPhone 5s");
capabilities.setCapability("newCommandTimeout", 600);
capabilities.setCapability("bundleId", "com.apple.mobilesafari");
capabilities.setCapability("useLocationServices", false);
wd = new IOSDriver(new URL(service_url), capabilities);
}
#BeforeMethod(alwaysRun = true)
public void beforeMethod(){
if(!service.isRunning())
{
service.start();
}
}
#AfterClass(alwaysRun = true)
public void killSimulatorAndAppium(){
service.stop();
}
}