Unable to capture screenshot in selenium - java

I am trying to capture screenshot in Selenium, However I am getting an error on -File source = ts.getScreenshotAs(OutputType.FILE); I have searched the code online and it they have given it as it is. Now I don't know what should be replaced with this code. The error I am getting is- FILE cannot be resolved or is not a field. My full code is:
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.aventstack.extentreports.Status;
import com.google.common.io.Files;
import com.mongodb.MapReduceCommand.OutputType;
public class UtilityMethods extends ExtentReportBaseClass{
static WebDriver driver;
public static WebDriver openBrowser(String browsers) {
System.out.println("initiated browser is " + browsers);
if (browsers.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.firefox.marionette", "");
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability("marionatte", false);
FirefoxOptions opt = new FirefoxOptions();
opt.merge(dc);
driver = new FirefoxDriver(opt);
}
else if (browsers.equalsIgnoreCase("Chrome")) {
// String driverPath = System.getProperty("user.dir") +
// "\\src\\Drivers\\chromedriver";
// System.setProperty("webdriver.chrome.driver", driverPath);
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
return driver;
}
public static void launchWebsite(String URL) {
driver.get(URL);
}
public static By locateByElement(String locator, String locatorValue) {
By by = null;
switch (locator) {
case "id":
by = By.id(locatorValue);
break;
case "name":
by = By.name(locatorValue);
break;
case "linktext":
by = By.linkText(locatorValue);
break;
case "partialLinkText":
by = By.partialLinkText(locatorValue);
break;
case "className":
by = By.className(locatorValue);
break;
case "tagName":
by = By.tagName(locatorValue);
break;
case "cssSelector":
by = By.cssSelector(locatorValue);
break;
case "xpath":
by = By.xpath(locatorValue);
break;
}
System.out.println("value of by is" + by);
return by;
}
public void sendDataById(String locatorValue, String userData) {
driver.findElement(By.id(locatorValue)).sendKeys(userData);
}
public void sendData(String element) {
String[] var = element.split("###");
String loctype = var[0];
String locval = var[1];
// System.out.println(locval);
String uservalue = var[2];
// System.out.println(locval);
// System.out.println(uservalue);
By locator = locateByElement(loctype, locval);
System.out.println(loctype);
System.out.println(locval);
driver.findElement(locator).sendKeys(uservalue);
}
public WebDriver getdriver() {
if (driver == null) {
driver = new FirefoxDriver();
return driver;
} else {
return driver;
}
}
public static String capture(WebDriver driver,String screenShotName) throws IOException
{
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String dest = System.getProperty("user.dir") +"/TestCasesScreenshot"+screenShotName+".png";
File destination = new File(dest);
Files.copy(source, destination);
return dest;
}
public void clickElement(String locElem) throws IOException {
try {
System.out.println(locElem);
String[] var = locElem.split("###");
String loctype = var[0];
String locval = var[1];
System.out.println(loctype);
System.out.println(locval);
By locator = locateByElement(loctype, locval);
driver.findElement(locator).click();
}
catch(Exception e)
{
System.out.println("Catched Exception, Element not found");
String screenShotPath = UtilityMethods.capture(driver, "screenShotName");
test.log(Status.FAIL, "Snapshot below: " + test.addScreenCaptureFromPath(screenShotPath));
}
}
}

You need to import selenium's OutputType. Use this -- import org.openqa.selenium.OutputType. Currently you have a mongodb class import.

Related

Unable to open browser in selenium, throws a "null" message

I have a framework that uses POM model and I have used a Utils folder structure which has DriverFactory,Constant and ReadConfigFile java files that configures and opens the browser. (code below)
Now before I did this (introducing the Utils package) the code was running fine and after introducing the Utils package i am getting "Unable to load browsernull" exception.
Not sure what is causing the problem. I am using a Mac machine.
Constant.java file:
package Utils;
public class Constant {
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties/config.properties";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir")+"CucumberFramework/src/test/java/Resources/geckodriver";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir")+"CucumberFramework/src/test/java/Resources/chromedriver";
}
DriverFactory.java file:
package Utils;
//import com.sun.java.util.jar.pack.Instruction;
import com.sun.tools.javac.code.Attribute;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import pageObjects.AddIssuePage;
import pageObjects.Login_Page;
import java.util.concurrent.TimeUnit;
public class DriverFactory {
public static WebDriver driver;
public static Login_Page login_page;
public static AddIssuePage addIssuePage;
public WebDriver getDriver() {
try
{
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
case "firefox":
if (null == driver) {
System.setProperty("webdriver.geckodriver", Constant.GECKO_DRIVER_DIRECTORY);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver();
}
break;
case "chrome":
if (null == driver) {
System.setProperty("webdriver.chromedriver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
}
break;
}
} catch (Exception e)
{
System.out.println("Unable to load browser" + e.getMessage());
} finally
{
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
login_page = PageFactory.initElements(driver, Login_Page.class);
}
return driver;
}
}
ReadConfigFile.java file:
package Utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile () {
try {
ReadConfigFile.class.getClassLoader ().getResourceAsStream (Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
}
Stacktrace:
java.lang.NullPointerException
at Utils.DriverFactory.getDriver(DriverFactory.java:63)
at Steps.MasterHooks.setup(MasterHooks.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at cucumber.runtime.Utils$1.call(Utils.java:40)
at cucumber.runtime.Timeout.timeout(Timeout.java:16)
at cucumber.runtime.Utils.invoke(Utils.java:34)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
java.lang.NullPointerException
at Utils.DriverFactory.getDriver(DriverFactory.java:63)
at Steps.MasterHooks.setup(MasterHooks.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at cucumber.runtime.Utils$1.call(Utils.java:40)
at cucumber.runtime.Timeout.timeout(Timeout.java:16)
at cucumber.runtime.Utils.invoke(Utils.java:34)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Process finished with exit code 1
MasterHooks
package Steps;
import Utils.DriverFactory;
import cucumber.api.java.After;
import cucumber.api.java.Before;
public class MasterHooks extends DriverFactory {
#Before
public void setup() {
driver = getDriver();
}
#After
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
This error message...
Unable to load browsernull
...implies that the function getBrowser() is returning null.
I would suggest the changes:
In ReadConfigFile.java:
Change:
ReadConfigFile.class.getClassLoader ().getResourceAsStream (Constant.CONFIG_PROPERTIES_DIRECTORY);
To:
File src = new File(Constant.CONFIG_PROPERTIES_DIRECTORY);
FileInputStream fis = new FileInputStream(src);
Properties prop = new Properties();
prop.load(fis);
Change:
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
To:
public String getBrowser(){
return prop.getProperty("browser");
}
In Constant.java
Change:
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties/config.properties";
To:
public final static String CONFIG_PROPERTIES_DIRECTORY = "./src/main/java/properties/config.properties";
In DriverFactory.java
Change:
"webdriver.geckodriver"
To:
"webdriver.gecko.driver"
Change:
"webdriver.chromedriver"
To:
"webdriver.chrome.driver"
The problem here is that, input instance variable of type Input Stream is assigned to null in Read config file class.
It should be assigned to input stream as given below.
package Utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile () {
try {
input = ReadConfigFile.class.getClassLoader ().getResourceAsStream (Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
}
Could you share your properties/config.properties file?
From the infos you shared I was thinking about that:
When, in DriverFactory, you call
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
In the getBrowser() there is:
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
So, if prop.getProperty("browser") is null, you are returning " " in browserName.
In the switch:
switch (browserName) {
case "firefox":
if (null == driver) {
System.setProperty("webdriver.geckodriver", Constant.GECKO_DRIVER_DIRECTORY);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver();
}
break;
case "chrome":
if (null == driver) {
System.setProperty("webdriver.chromedriver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
}
break;
}
} catch (Exception e)
{
System.out.println("Unable to load browser" + e.getMessage());
} finally
{
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
login_page = PageFactory.initElements(driver, Login_Page.class);
}
I don't see any check in the case browserName is " " or in another case (I mean, there isn't a default case). So, in case browserName is " " or something else different of "firefox" or "chrome" you go directly to the finally statement (the finally is always executed). In this case, because the driver is not instantiated, you will have a nullpointer exception in:
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);

How to get cookie value from a WebDriver using selenium?

/I am using the following code to get the cookie value but I am only getting 1st and 2nd part.But not getting 3rd and 4th part(null as you can see).
Please help me with this.I have attached the screenshot of the cookies i get manually/
WebDriver driver;
System.setProperty("webdriver.ie.driver",
"C:\\Users\\MR049860\\Documents\\Selenium\\IEDriverServer\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("https://www.example.com");
// Input Email id and Password If you are already Register
driver.findElement(By.name("j_username")).sendKeys("publisher");
driver.findElement(By.name("j_password")).sendKeys("Passw0rd");
WebDriverWait wait = new WebDriverWait(driver, 5);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("BtnButton__")));
// WebElement ele = driver.findElement(By.id("ctllogonBtnButton__"));
element.sendKeys(Keys.ENTER);
// create file named Cookies to store Login Information
File file = new File("madhu.data");
try
{
// Delete old file if exists
file.delete();
file.createNewFile();
FileWriter fileWrite = new FileWriter(file);
BufferedWriter Bwrite = new BufferedWriter(fileWrite);
// loop for getting the cookie information
// loop for getting the cookie information
for(Cookie ck : driver.manage().getCookies())
{
Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));
Bwrite.newLine();
}
Bwrite.close();
fileWrite.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
Output : -
ASPSESSIONIDSZQPRQCS;NFPFIAGDBMJNOMKPCPKESHDC;null;/;null;true
You can get only name and value. You are not allowed to get cookies of other domains/paths or expiry date. That's the security policy of web browsers.
Below code can be used to get the cookie value
package utility;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CookieUtility {
public static InternetExplorerDriver getDriver() throws InterruptedException {
InternetExplorerDriver driver;
System.setProperty("webdriver.ie.driver",
"C:\\Documents\\Selenium\\IEDriverServer\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("https://example.com");
// Input Email id and Password If you are already Register
driver.findElement(By.name("username")).sendKeys("password");
driver.findElement(By.name("password")).sendKeys("Paswrd");
WebDriverWait wait = new WebDriverWait(driver, 5);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("logonButton")));
// WebElement ele = driver.findElement(By.id("ctllogonBtnButton__"));
element.sendKeys(Keys.ENTER);
for (int i = 0; i < 2 && driver.findElements(By.id("textbox")).size() == 0; i++) {
Thread.sleep(10000);
}
element.sendKeys(Keys.F5);
return driver;
}
public static String[] getCookieValues(InternetExplorerDriver driver) throws InterruptedException {
// create file named Cookies to store Login Information
Set<Cookie> cks = driver.manage().getCookies();
String[] cookieValues = new String[cks.size()];
int i = 0;
for (Cookie ck : cks) {
cookieValues[i] = ck.getValue();
i++;
}
i = 0;
return cookieValues;
}
public static String getSessionId(InternetExplorerDriver driver) {
String sessionId = driver.getSessionId().toString();
return sessionId;
}
public static void main(String args[]) throws InterruptedException {
InternetExplorerDriver driver = getDriver();
String[] values = getCookieValues(driver);
String sessionId = getSessionId(driver);
}
public static String getcookiestring(String sessionId, String cookie1, String cookie2, String cookie3) {
String cookie = "JSESSIONID=" + sessionId + "; hi.session.co.entity=" + cookie2 + "; hi.session.id.identifier="
+ cookie1 + "; hi.session.client.identifier=" + cookie3;
return cookie;
}
}

Selenium webdriver gecko error: The path to the driver must be set by webdriver.gecko

trying to get selenium working but didn't work and showing me below error.
Libs:junit4.12, selenium-java-3.4, selenium-server-standalone-3.5
Could anyone take a look and tell me whats wrong with the code or what is
missing, please.
Every time when I start the test, I get 2 errors.
Screenshot embedded at the bottom showing the error details.
My code as below:
package com.example.tests;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;
public class TestCase16 {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "URL";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.setProperty("webdriver.gecko.driver", "C:\\Users\\ayre1de\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("URL");
}
#Test
public void testCaseAcandoIntranet() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("IDToken1")).clear();
driver.findElement(By.id("IDToken1")).sendKeys("XXX");
driver.findElement(By.id("IDToken2")).clear();
driver.findElement(By.id("IDToken2")).sendKeys("*XXX");
driver.findElement(By.name("Login.Submit")).click();
driver.findElement(By.id("yui_patched_v3_18_1_1_1502961326988_317")).click();
driver.findElement(By.xpath("//a[#id='_com_liferay_product_navigation_user_personal_bar_web_portlet_ProductNavigationUserPersonalBarPortlet_sidenavUserToggle']/span/div")).click();
driver.findElement(By.linkText("Abmelden")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
`
The problem is you are initializing webdriver instance two times like below. specially you have missed specifying the System.setProperty for the first instance of webdriver where exactly your code is failing:-
driver = new FirefoxDriver(); // 1st instance
baseUrl = "URL";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.setProperty("webdriver.gecko.driver", "C:\\Users\\ayre1de\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver(); // 2nd instance
driver.get("URL");
Now delete above two lines and write your code like below :-
System.setProperty("webdriver.gecko.driver", "C:\\Users\\ayre1de\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("URL");

Selenium Java - java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property

My FireFox Version 49.0.1
Selenium Version: Selenium-java-3.0.0-beta3
Java: 8.0.1010.13
I have replaced all the existing Selenium Jar Files with the new files. Added the gecko.Driver to my code still I am seeing this message:
Error Message:
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property;
My Code:
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AbstractPage {
WebDriver Driver =new FirefoxDriver();
#Before
public void Homescreen() throws InterruptedException
{
System.getProperty("Webdriver.gecko.driver", "C:/geckodriver.exe");
System.setProperty("Webdriver.firefox.bin", "C:/Program Files (x86)/Mozilla Firefox/firefox.exe");
Driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Driver.get("URL");
Driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#After
public void TestComplete() {
Driver.close();
}
#Test
public void Projects() {
Driver.findElement(By.id("login-form-username")).sendKeys("Login");
Driver.findElement(By.id("login-form-password")).sendKeys("Password");
Driver.findElement(By.id("quickSearchInput")).sendKeys("ID");
}
}
You can remove main() method from the code. unzip your gecko driver and save it to your local system with wires.exe.
my sample class path is
G:\ravik\Ravi-Training\Selenium\Marionette for firefox\wires.exe
public class AbstractPage
{
WebDriver Driver;
System.setProperty("WebDriver.gecko.Driver", "C:\\TEMP\\Temp1_geckodriver-v0.10.0-win64.zip");
Driver=new FirefoxDriver();
#Before
public void Homescreen() throws InterruptedException
{
Driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Driver.get("https://QualityAssurance.com");
Driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Driver.findElement(By.id("login-form-username")).sendKeys("Login");
Driver.findElement(By.id("login-form-password")).sendKeys("Password");
//JavascriptExecutor js = (JavascriptExecutor) Driver;
//js.executeScript("document.getElementById('login-form-password').setAttribute('value', val );");
}
#After
public void TestComplete() {
Driver.close();
}
#Test
public void Projects() {
Driver.findElement(By.id("quickSearchInput")).sendKeys("WMSSE-229");
Please replace below line
System.setProperty("WebDriver.gecko.Driver", C:\\TEMP\\Temp1_geckodriver-v0.10.0-win64.zip");
You should pass geckodriver.exe not Zip file.
String driverPath = "F:/Sample/Selenium3Example/Resources/";
System.setProperty("webdriver.firefox.marionette", driverPath+"geckodriver.exe");
You can make your code more cleaner when posting here.
You must do something like this:
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
System.setProperty("webdriver.firefox.bin", "C:/Program Files (x86)/Mozilla Firefox/firefox.exe");
This is a working example, it make you know the context what the above code snippet used
package selenium;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Junit4FirefoxJava {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
System.setProperty("webdriver.firefox.bin", "C:/Program Files (x86)/Mozilla Firefox/firefox.exe");
driver = new FirefoxDriver();
baseUrl = "http://www.bing.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testJunit4IeJava() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("sb_form_q")).click();
driver.findElement(By.id("sb_form_q")).clear();
driver.findElement(By.id("sb_form_q")).sendKeys("NTT data");
driver.findElement(By.id("sb_form_go")).click();
driver.findElement(By.linkText("NTT DATA - Official Site")).click();
driver.findElement(By.id("js-arealanguage-trigger")).click();
driver.findElement(By.linkText("Vietnam - English")).click();
driver.findElement(By.id("MF_form_phrase")).clear();
driver.findElement(By.id("MF_form_phrase")).sendKeys("internet");
driver.findElement(By.cssSelector("input.search-button")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}

How to upload Multiple files in selenium?

I'm trying to use following code :-
driver.findElement(By.xpath(".//*[#id='attach0']")).sendKeys("first path"+"\n"+"second path""+"\n"third path");
I didn't get result.
you can use AutoIT or JAVA code. Below i have used both for your reference. Try anyone of them
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
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.remote.DesiredCapabilities;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AutoITforUpload {
private static WebDriver driver;
private static WebDriverWait waitForElement;
#FindBy(css = "span.btn.btn-success.fileinput-button")
private WebElement Add_files_btn;
#BeforeClass
public static void setUp() {
DesiredCapabilities desicap = new DesiredCapabilities();
System.setProperty("webdriver.chrome.driver", "D:/WorkSpace/Driver/chromedriver.exe");
desicap = DesiredCapabilities.chrome();
driver = new ChromeDriver(desicap);
driver.manage().window().maximize();
driver.get("https://blueimp.github.io/jQuery-File-Upload/");
waitForElement = new WebDriverWait(driver, 30);
}
#Test
public void AutoitUpload() {
// String filepath =
// "D:/Mine/GitHub/BasicProgramLearn/AutoItScript/unnamed.png";
WebElement btn = driver.findElement(By.cssSelector("span.btn.btn-success.fileinput-button"));
String file_dir = System.getProperty("user.dir");
String cmd = file_dir + "\\AutoItScript\\unnamed.png";
System.out.println("File directory is " + file_dir);
try {
// Using ordinary
Thread.sleep(3000);
for(int i=0;i<3;i++) //multiple times upload ;
driver.findElement(By.xpath("//*[#id='fileupload']/div/div[1]/span[1]/input")).sendKeys(cmd);
//use any String Array for multiple files
waitForElement(btn);
btn.click();
Thread.sleep(3000);
System.out.println(file_dir + "/AutoItScript/FileUploadCode.exe");
Runtime.getRuntime().exec(file_dir + "\\AutoItScript\\ChromeFileUpload.exe" + " " + cmd);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
#AfterClass
public static void TearDown() {
try {
Thread.sleep(5000);
driver.quit();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void waitForElement(WebElement vElement) {
waitForElement.until(ExpectedConditions.visibilityOf(vElement));
}
}
The code in AutoIt is
#include<IE.au3>
If $CmdLine[0] < 2 Then
$window_name="Open"
WinWait($window_name)
ControlFocus($window_name,"","Edit1")
ControlSetText($window_name,"","Edit1",$CmdLine[1])
ControlClick($window_name,"","Button1")
EndIf
Hope this gives you an idea

Categories