I tried to run simple Java Selenium code but am getting this error - can anyone help me to figure it out?
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class test
{
public static void main(String[] args)
{
stem.setProperty("webdriver.chrome.driver","D:/apache-jmeter-3.1/bin/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
String Title = driver.getTitle();
//compare the actual title of the page with the expected one
if (Title.contentEquals("Google"))
{
System.out.println("Test Passed!");
}
else
{
System.out.println("Test Failed");
}
driver.close();
}
}
It seems you are using incorrect url in get() method. Try to use get() method like below:
driver.get("http://www.google.com");
URL must contains "http://" or "https://" to define its protocol.
Fix in your code, you can try below once inside WebDriver Sampler :
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class test {
public static void main(String[] args) {
try{
System.setProperty("webdriver.chrome.driver","D:/apache-jmeter-
3.1/bin/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
String Title = driver.getTitle();
if (Title.contentEquals("Google")){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
driver.close();
} catch (Exception e){}
}
}
Use this:
System.setProperty("webdriver.chrome.driver","D://apache-jmeter-3.1//bin//chromedriver.exe");
As described in the javadoc for the System class:
Sets the system property indicated by the specified key.
First, if a security manager exists, its
SecurityManager.checkPermission method is called with a
PropertyPermission(key, "write") permission. This may result in a
SecurityException being thrown. If no exception is thrown, the
specified property is set to the given value.
Parameters:
key - the name of the system property. value - the value of the
system property.
Returns:
the previous value of the system property, or null if it did not have
one. Throws: SecurityException - if a security manager exists and
its checkPermission method doesn't allow setting of the specified
property. NullPointerException - if key or value is null.
IllegalArgumentException - if key is empty.
Related
I am a beginner in Selenium. I do not have any hands on experience in it. Last month I had enrolled for a Selenium beginner to advanced course where I have few activities where I can do hands on.
I am stuck at a certain place. Let me explain my issue.
This is the activity description:
RelativeXpathLocator
URL: http://webapps.tekstac.com/Shopify/
Test Procedure:
Use the template code.
Don't make any changes in DriverSetup file.
Only in the suggested section add the code to,
Invoke the driver using getWebDriver() method defined in DriverSetup()
Identify the web element of the value 'SivaKumar' using xpath locator and return it.
Using the same web element, get the text and return it.
The code that I wrote for this:
//Add required imports
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
public class RelativeXpathLocator //DO NOT Change the class Name
{
static WebDriver driver;
static String baseUrl = "http://webapps.tekstac.com/Shopify/";
public WebDriver createDriver() //DO NOT change the method signature
{
DriverSetup ds = new DriverSetup();
return ds.getWebDriver();
//Implement code to create Driver from DriverSetup and return it
}
public WebElement getRelativeXpathLocator(WebDriver driver)//DO NOT change the method signature
{
WebElement l = driver.findElement(By.xpath("//*[#id='tbrow']/td[3]"));
return (l);
/*Replace this comment by the code statement to get the Web element */
/*Find and return the element */
}
public String getName(WebElement element)//DO NOT change the method signature
{
return element.getAttribute("tbrow");
//Get the attribute value from the element and return it
}
public static void main(String[] args){
RelativeXpathLocator pl=new RelativeXpathLocator();
driver = pl.createDriver();
//WebElement les = pl.getRelativeXpathLocator(driver);
//String las = pl.getName(les);
//Add required code
}
}
Kinda stuck here. Not sure what mistake I've made in getname or main().
The ending portion is throwing error while compiling. Says "Unable to locate name using xpath expected: but was:
Please advise.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
public class RelativeXpathLocator //DO NOT Change the class Name
{
static WebDriver driver;
static String baseUrl = "http://webapps.tekstac.com/Shopify/";
public WebDriver createDriver() //DO NOT change the method signature
{
DriverSetup ds = new DriverSetup();
return ds.getWebDriver();
//Implement code to create Driver from DriverSetup and return it
}
public WebElement getRelativeXpathLocator(WebDriver driver)//DO NOT change the method signature
{
WebElement element = driver.findElement(By.xpath("//tr[#id='tbrow']/td[3]"));
return element;
/*Replace this comment by the code statement to get the Web element */
/*Find and return the element */
}
public String getName(WebElement element)//DO NOT change the method signature
{
return element.getText();
//Get the attribute value from the element and return it
}
public static void main(String[] args){
RelativeXpathLocator pl=new RelativeXpathLocator();
driver = pl.createDriver();
//WebElement les = pl.getRelativeXpathLocator(driver);
//String las = pl.getName(les);
//Add required code
}
}
I am trying to create a selenium script using get(int) method undefined for the type list that will select a radio button if it is not selected.
I use the following script:
package automationFramework;
import java.awt.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FirstTestCase {
public static void main(String[] args) throws InterruptedException {
// Create a new instance of the Firefox driver
System.setProperty("webdriver.gecko.driver", "/home/gradulescu/Documents/Eclipse project/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
// Storing the Application Url in the String variable
String url = "http://toolsqa.wpengine.com/automation-practice-form/";
driver.get(url);
//Launch the Online Store Website
List Rbtn = (List) driver.findElement(By.name("sex"));
boolean bool = false;
bool = Rbtn.get(0).isSelected();
if (bool==true)
{Rbtn.get(1).click();
}
else
{Rbtn.get(0).click();
}
}
}
The get method returns the following error:
method get(int) is undefined for the type list
I use Eclipse 3.8.1 with JConsole 1.8.0_171-b11 and Java VM version: Java HotSpot(TM) 64-Bit Server VM, 25.171-b11
Can you help me with that?
As states the doc of WebDriver, the findElements(By by) method returns a java.util.List<WebElement>(list of object of WebElement class) and not a java.awt.List (list of UI component in awt).
You need to change your import, and the code to :
List<WebElement> rbtn = driver.findElement(By.name("sex"));
note : in Java, variables, parameters, methods names have to sart with a lowercase letter
Replace:
List Rbtn = (List) driver.findElement(By.name("sex"));
with:
List<WebElement> rBtn = driver.findElements(By.name("sex")); // this will return a list of all found elements
This a sample workable code:
driver.get("http://toolsqa.wpengine.com/automation-practice-form/");
List<WebElement> rBtn = driver.findElements(By.name("sex")); // this will return a list of all found elements
if (rBtn.get(1).isSelected()) // I'm getting the second element because the first one is only label
{
rBtn.get(2).click(); //click 'Female'
}
else
{
rBtn.get(1).click(); //click 'Male'
}
PS: always check in dev tools which elements you are locating with your selector. To open dev tools press F12 in browser. More information here.
boolean is false by default so you don't have to explicitly initialize it. Similarly, if(bool) will do. Thirdly, you need to use findElements when you are storing them in List. Fourth, its a good practice to use try...catch block.
Try -
package automationFramework;
import java.awt.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FirstTestCase {
public static void main(String[] args){
try {
System.setProperty("webdriver.gecko.driver", "/home/gradulescu/Documents/Eclipse project/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
// Storing the Application Url in the String variable
String url = "http://toolsqa.wpengine.com/automation-practice-form/";
driver.get(url);
// Launch the Online Store Website
List<WebElement> Rbtn = driver.findElements(By.name("sex"));
boolean bool;
bool = Rbtn.get(0).isSelected();
if (bool)
Rbtn.get(1).click();
else
Rbtn.get(0).click();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Till yesterday the below mentioned code was working fine but now i am facing some problem .
The code opens firefox browser then loads facebook.com but the code is not sending
email and password to web browser i.e. sendkeys() is not working.
I verified the id of both textbox of email and password which are correct yet code is not working .
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
public class Webdriver2 {
WebDriver driver ;
JavascriptExecutor jse;
public void invokeBrowser()
{
try
{
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.19.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS );
driver.get("https://www.facebook.com/");
search();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void search()
{
try
{
driver.findElement(By.id("email")).sendKeys("example#gmail.com");
Thread.sleep(4000);
driver.findElement(By.id("pass")).sendKeys("password");
Thread.sleep(4000);
driver.findElement(By.id("u_0_2")).click();
Thread.sleep(4000);
/*driver.findElement(By.name("q")).sendKeys("spit mumbai");
Thread.sleep(4000);
driver.findElement(By.xpath(" //button[#aria-label='Search' and #data-testid='facebar_search_button'] ")).click();*/
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Webdriver2 w = new Webdriver2();
w.invokeBrowser();
}
}
Try clicking on the two textboxes before you are performing the sendKeys:
driver.findElement(By.id("email")).click();
driver.findElement(By.id("email")).sendKeys("example#gmail.com");
The textboxes probably needs focus.
We need to take care of a couple of things here as follows:
The Email or Phone field is within an <input> tag so we need to take it into account while selecting the locator.
The Password field is also within an <input> tag so we need to take it into account while selecting the locator.
If you observe closely the id of the Log In button is dynamic and also within an <input> tag, so we need to consider this factor as well.
Here is the minimum sample code block using cssSelector to access the url https://www.facebook.com/, provide Email or Phone and Password, finally click on Log In button:
package demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Facebook_Login_CSS_FF {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.findElement(By.cssSelector("input#email")).sendKeys("Ryusei");
driver.findElement(By.cssSelector("input[name='pass']")).sendKeys("Nakamura");
driver.findElement(By.cssSelector("input[value='Log In']")).click();
}
}
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 click on a web element using Selenium WebDriver(2.21.0).
When I try driving through the Selenium IDE it works properly but when I try the same set of actions using the Java implementation of Firefox driver- it leads to the wrong page.
While the code is running and I manually scroll to the desired element, it works.
I am making sure that the web element is visible and enabled using
By by = By.xpath("(//a[contains(#href, 'javascript:void(0);')])[26]"); //**Edit:** this is how i
//am getting the locator
WebElement element = driver.findElement(by);
return (element.isEnabled() || element.isDisplayed()) ? element : null;
which returns some element but not the one I am expecting.
This looks strange to me as Selenium webdriver mostly scrolls to an element(if not visible on the screen) by itself and does the required interaction.
I have tried some answers like one, two with no success.
Thanks in advance!
EDIT: here is the IDE's exported code(java/JUnit4/webdriver)
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.support.ui.Select;
public class Bandar {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://e.weibo.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testBandar() throws Exception {
driver.get(baseUrl + "/nescafechina");
driver.findElement(By.xpath("(//a[contains(#href, 'javascript:void(0);')])[26]")).click();
driver.findElement(By.xpath("(//a[contains(#href, 'javascript:void(0);')])[12]")).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;
}
}
}
Ishank,
What I have done is gone through and created a test that shows the different kind of asserts that you can use in your testing. They do look a little different from what you are looking at, I feel your main problem is WebElement element = driver.findElement(by); because you are not giving it an actual element. The (by); section is looking for a string that can be found on the page. Acceptable strings would be; id("gbfqb"); or xpath("(//a[contains(#href, 'javascript:void(0);')])[26]"); or even name("find-button");.
/**
* Test the main Google page.
* #throws InterruptedException
*
*/
#Test
public void signUp() throws InterruptedException {
String testId = "TestStack01";
entered(testId);
webDriver.get("www.google.com");
webDriver.findElement(By.id("gbqfq")).clear();
webDriver.findElement(By.id("gbqfq")).sendKeys("Test");
assertEquals("", webDriver.findElement(By.id("gbqfb")).getText());
WebElement whatyourlookingfor = webDriver.findElement(By.id("gbqfb"));
assertTrue(selenium.isElementPresent("gbqfb"));
assertTrue(whatyourlookingfor.isEnabled());
assertTrue(whatyourlookingfor.isDisplayed());
assertFalse(whatyourlookingfor.isSelected());
webDriver.findElement(By.id("gbqfb")).click();
leaving(testId);
}
I hope that this has helped in getting which element is being returned.
Curtis Miller