I'm currently taking my first automated test class and the instructor has us creating a program in Eclipse after loading Selenium and create a step in the program to look at an executable to bring up chrome then designate a website to check. It looks like i am stuck in a loop?
Here is the program:
java program
Here is the result:
program result
any and all help would be appreciated. Thank you for your time.
I think this is what you want
This code is to open the default browser and go to a specific link
You can specify the path of any browser you want from the path in the code
import java.awt.Desktop;
import java.net.URI;
public class openBrowser {
public openBrowser() {
try {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("https://www.google.com"));
}
}catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[]args) {
new openBrowser();
}
}
For your code you can follow the following steps
Download ChromeDriver from here
Extract the zip file and follow the path ( because it is easy ) C:\\chromeDriver\\chromedriver.exe
include the ChromeDriver location in your PATH environment variable
Download the required Libraries from the following junit openqa
Add the Libraries to your project ( Build Path )
then this is your code
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.junit.Test;
public class WebDriverDemo {
#Test
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\chromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(WebDriverDemo.class.getName()).log(Level.SEVERE, null, ex);
}
driver.quit();
}
}
During the implementation of the code in the eclipse, many problems occurred, so I advise you to implement the project on NetBeans
I use Java 8 and Windows 8.1
Related
I am a total noob at Automation Testing and i am trying to learn through Youtube how to do it.
https://youtu.be/FRn5J31eAMw?t=12405
On this course from Edureka there is an example where they are trying to handle an exception, where after they run the script the system shows them a message in the console which i cannot get.
package co.edureka.selenium.demo;
import java.util.NoSuchElementException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandlingExceptions {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
Thread.sleep(3000);
try {
driver.findElement(By.name("fake")).click();
}catch (NoSuchElementException e) {
System.out.println("element is not found");
System.out.println("Hello");
//throw(e);
}
System.out.println("Hello");
}
}
this is the script in Java they are running and at the end in the console they are getting this as a result
Edureka Console
But i am getting something totally different even though my code is exactly the same.
My Console
What am i doing wrong?
your are using "import java.util.NoSuchElementException;
" at top of file so please remove and use below one
org.openqa.selenium.NoSuchElementException
I have written the following code in JAVA using Selenium web driver using both Internet Explorer and Firefox. Everytime I am getting the same error. Tried using both "id" and "xpath" method, but still it is failing. Tried adding some delay also, still does not work.
My JAVA code for Firefox:
package ieconnector;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class FireFoxConnector {
public static void main(String[] args) {
try{
GetBrowserProperty gbp = new GetBrowserProperty();
System.setProperty("webdriver.ie.driver",gbp.getIeConnection());
System.setProperty("webdriver.gecko.driver","D:\\softwares\\Selenium\\geckodriver-v0.21.0-win64\\geckodriver.exe");
WebDriver wb = new FirefoxDriver();
Capabilities caps = ((RemoteWebDriver) wb).getCapabilities();
System.out.println("Caps is "+caps);
wb.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//wb.navigate().to("https://somewebsite.com:22222/SSO/ui/SSOLogin.jsp");
wb.get("https://somewebsite.com:22222/SSO/ui/SSOLogin.jsp");
wb.manage().deleteAllCookies();
wb.manage().window().maximize();
//wb.findElement(By.id("usertxt")).sendKeys(("user").toUpperCase());
//wb.findElement(By.className("passtxt")).sendKeys("password");
//WebDriverWait wait = new WebDriverWait(wb,10);
//WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("usertxt")));
wb.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
//wb.findElement(By.id("usertxt")).sendKeys("USER");
wb.findElement(By.xpath("//*[#id='usertxt']")).sendKeys("USER");
System.out.println("Testing is successful");
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the following is a screenshot of the HTML code in my developer tool in IE/Firefox.
As per the HTML you have shared to locate the User ID field you can use the following solution:
cssSelector:
wb.findElement(By.cssSelector("input.txtbox#usertxt")).sendKeys("USER");
xpath:
wb.findElement(By.xpath("//input[#class='txtbox' and #id='usertxt']")).sendKeys("USER");
This is my code.
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "data/chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "logs/ss/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
}
All time when driver.get() throw TimeoutException I want to take a screenshot at browser.
But when throw TimeoutException, getScreenshotAs() from printSS() don't take screenshot because throw another TimeoutException.
Why getScreenshotAs() throw TimeoutException and how to take screenshot at browser
P.S.: Increase pageLoadTimeout time is not the answer I want.
While working with Selenium 3.x, ChromeDriver 2.36 and Chrome 65.x you need to mention the relative path of the location (with respect of your project) where you intend to store the screenshot.
I took you code and did a few minor modification as follows :
Declared driver as WebDriver instance as static and added #Test annotation.
Reduced pageLoadTimeout to 2 seconds to purposefully raise the TimeoutException.
Changed the location of String path to a sub-directory wthin the project scope as follows :
String path = "./ScreenShots/";
Added a log as :
System.out.println("Screenshot Taken");
Here is the code block :
package captureScreenShot;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class q49319748_captureScreenshot
{
public static WebDriver drive;
#Test
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "./ScreenShots/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
System.out.println("Screenshot Taken");
}
}
Console Output :
[TestNG] Running:
C:\Users\username\AppData\Local\Temp\testng-eclipse--153679036\testng-customsuite.xml
Starting ChromeDriver 2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91) on port 42798
Only local connections are allowed.
Mar 16, 2018 5:37:59 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Screenshot Taken
PASSED: test1
Screenshot :
Reference
You can find a detailed discussion in How to take screenshot with Selenium WebDriver
The problem is that while Selenium waits for the page to complete loading it cannot take any other command. This is why it throws TimeoutException also from the exception handler when you try take the screenshot.
The only option I see is to take the screenshot not through Selenium, but using other means that take a screenshot of the entire desktop. I've written such a thing in C#, but I'm pretty sure you can either find a way to do it in Java too.
Basically every time I run my java code from eclipse, webdriver launches a new ie browser and executes my tests successfully for the most part. However, I have a lot of tests to run, and it's a pain that webdriver starts up a new browser session every time. I need a way to re-use a previously opened browser; so webdriver would open ie the first time, then the second time, i run my eclipse program, I want it to simply pick up the previous browser instance and continue to run my tests on that same instance. That way, I am NOT starting up a new browser session every time I run my program.
Say you have 100 tests to run in eclipse, you hit that run button and they all run, then at about the 87th test you get an error. You then go back to eclipse, fix that error, but then you have to re-run all 100 test again from scratch.
It would be nice to fix the error on that 87th test and then resume the execution from that 87th test as opposed to re-executing all tests from scratch, i.e from test 0 all the way to 100.
Hopefully, I am clear enough to get some help from you guys, thanks btw.
Here's my attempt below at trying to maintain and re-use a webdriver internet explorer browser instance:
public class demo extends RemoteWebDriver {
public static WebDriver driver;
public Selenium selenium;
public WebDriverWait wait;
public String propertyFile;
String getSessionId;
public demo() { // constructor
DesiredCapabilities ieCapabilities = DesiredCapabilities
.internetExplorer();
ieCapabilities
.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
driver = new InternetExplorerDriver(ieCapabilities);
this.saveSessionIdToSomeStorage(getSessionId);
this.startSession(ieCapabilities);
driver.manage().window().maximize();
}
#Override
protected void startSession(Capabilities desiredCapabilities) {
String sid = getPreviousSessionIdFromSomeStorage();
if (sid != null) {
setSessionId(sid);
try {
getCurrentUrl();
} catch (WebDriverException e) {
// session is not valid
sid = null;
}
}
if (sid == null) {
super.startSession(desiredCapabilities);
saveSessionIdToSomeStorage(getSessionId().toString());
}
}
private void saveSessionIdToSomeStorage(String session) {
session=((RemoteWebDriver) driver).getSessionId().toString();
}
private String getPreviousSessionIdFromSomeStorage() {
return getSessionId;
}
}
My hope here was that by overriding the startSession() method from remoteWebdriver, it would somehow check that I already had an instance of webdriver browser opened in i.e and it would instead use that instance as opposed to re-creating a new instance everytime I hit that "run" button in eclipse.
I can also see that because I am creating a "new driver instance" from my constructor, since constructor always execute first, it creates that new driver instance automatically, so I might need to alter that somehow, but don't know how.
I am a newbie on both stackoverflow and with selenium webdriver and hope someone here can help.
Thanks!
To answer your question:
No. You can't use a browser that is currently running on your computer. You can use the same browser for the different tests, however, as long as it is on the same execution.
However, it sounds like your real problem is running 100 tests over and over again. I would recommend using a testing framework (like TestNG or JUnit). With these, you can specify which tests you want to run (TestNG will generate an XML file of all of the tests that fail, so when you run it, it will only execute the failed tests).
Actually you can re-use the same session again..
In node client you can use following code to attach to existing selenium session
var browser = wd.remote('http://localhost:4444/wd/hub');
browser.attach('df606fdd-f4b7-4651-aaba-fe37a39c86e3', function(err, capabilities) {
// The 'capabilities' object as returned by sessionCapabilities
if (err) { /* that session doesn't exist */ }
else {
browser.elementByCss("button.groovy-button", function(err, el) {
...
});
}
});
...
browser.detach();
To get selenium session id,
driver.getSessionId();
Note:
This is available in Node Client only..
To do the same thing in JAVA or C#, you have to override execute method of selenium to capture the sessionId and save it in local file and read it again to attach with existing selenium session
I have tried the below steps to use the same browser instance and it worked for me:
If you are having generic or Class 1 in different package the below code snippet will work -
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
// Class 1 :
public class Generics {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "url";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
// Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import zgenerics.Generics;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends Generics {
#Test
public void Login() throws InterruptedException, Exception {
WebDriverWait wait = new WebDriverWait(driver,25);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
driver.findElement(By.cssSelector("")).sendKeys("");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
driver.findElement(By.xpath("")).sendKeys("");
}
}
If your Generics class is in the same package you just need to make below change in your code:
public class Generics {
public Generics(){}
WebDriver driver; }
Just remove the protected word from Webdriver code line. Rest code of class 1 remain as it is.
Regards,
Mohit Baluja
I have tried it by extension of classes(Java Inheritance) and creating an xml file. I hope below examples will help:
Class 1 :
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
public class SetUp {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "URL";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import zgenerics.SetUp
public class Conditions extends SetUp {
#Test
public void visible() throws InterruptedException{
Thread.sleep(5000);
boolean signINbutton=driver.findElement(By.xpath("xpath")).isEnabled();
System.out.println(signINbutton);
boolean SIGNTEXT=driver.findElement(By.xpath("xpath")).isDisplayed();
System.out.println(SIGNTEXT);
if (signINbutton==true && SIGNTEXT==true){
System.out.println("Text and button is present");
}
else{
System.out.println("Nothing is visible");
}
}
}
Class 3:
package automationScripts;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
public class Footer extends Conditions {
#Test
public void footerNew () throws InterruptedException{
WebElement aboutUs = driver.findElement(By.cssSelector("CssSelector"));
aboutUs.click();
WebElement cancel = driver.findElement(By.xpath("xpath"));
cancel.click();
Thread.sleep(1000);
WebElement TermsNCond = driver.findElement(By.xpath("xpath"));
TermsNCond.click();
}
}
Now Create an xml file with below code for example and run the testng.xml as testng suite:
copy and paste below code and edit it accordingly.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="classes" thread-count="3">
<test name="PackTest">
<classes>
<class name="automationScripts.Footer"/>
</classes>
This will run above three classes. That means one browser and different tests.
We can set the execution sequence by setting the class names in alphabetical order as i have done in above classes.
I am trying to login to our company product site via selenium.I am able to do it via the Selenium IDE. And this is the code that the IDE exports using JUnit4(Remote Control):
package com.beginning;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.regex.Pattern;
public class testcase extends SeleneseTestCase {
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "link");
selenium.start();
}
#Test
public void testTestcase() throws Exception {
selenium.open("complete link");
selenium.type("name=j_username", "username");
selenium.type("name=j_password", "password");
selenium.click("css=input[type=\"submit\"]");
selenium.waitForPageToLoad("30000");
//selenium.click("link=Sign out");
//selenium.waitForPageToLoad("30000");
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
My doubts are :
1.Why does selenium IDE export the browser type as *chrome when I am actually doing it in firefox.
2.If I use the test as it is, it enters the values and then gives an exception .
3.If I change the browser Type to *firefox, it starts execution but nothing happens at all. Basically hangs.
Things work fine when doing it from the IDE.
Thanks.
Change your "link" (4th parameter of DefaultSelenium constructor) so it's actually a valid URL (the site you want to target)
Would reccommend you to check the version of firefox and upgrade to latest.I have used a similar scenario. Pls find the code below.
You can use this its works grt.Hope you find it useful.
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class TestRun {
public static void main(String[] args)
{
Selenium selenium=new DefaultSelenium("localhost", 4444 , "*firefox","myurl");
selenium.start();
selenium.open("myurl");
System.out.println("Open browser "+selenium);
selenium.windowMaximize();
selenium.type("id=j_username","Lal");
selenium.type("name=j_password","lal");
selenium.click("name=submit");
**selenium.waitForPageToLoad("60000");**
if(selenium.isTextPresent("Lal"))
{
selenium.click("id=common_header_logout");
}
else
{
System.out.println("User not found");
}
}
}