I tried to automate the MakeMyTrip site ,I am getting a stale element reference error in line number 42 which i have highlighted .. I have tried all possible solutions..could u please help me with it ..
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import net.bytebuddy.asm.Advice.Return;
public class Dropdown {
#SuppressWarnings("deprecation")
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\arthi\\ChromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
Actions act = new Actions(driver);
driver.get("https://www.makemytrip.com/");
driver.manage().window().maximize();
WebElement Fromcity = driver.findElement(By.id("fromCity"));
act.doubleClick(Fromcity).perform();
Thread.sleep(1000);
WebElement From = driver.findElement(By.xpath("//*[#placeholder='From']"));
act.doubleClick(From).perform();
From.sendKeys("chenn");
//List Fromcities=driver.findElements(By.xpath("//*[#id='react-autowhatever-1']/div[1]/ul/li/div/div[1]/p"));
List<WebElement> Fromcities = driver.findElements(By.xpath("//ul[#role='listbox']//li/div[1]/div[2]"));
for (WebElement Cities : Fromcities)
{
String Citi = Cities.getText();
**if (Citi.equals("MAA"))** {
try {
Cities.click();
} catch (StaleElementReferenceException ex) {
Fromcities = driver
.findElements(By.xpath("//*[#id='react-autowhatever-1']/div[1]/ul/li/div/div[1]/p"));
Cities.click();
}
}
}
//***to path
driver.findElement(By.xpath("//input[#placeholder='To']")).click();
WebElement ToPlace = driver.findElement(By.xpath("//input[#placeholder='To']"));
act.doubleClick(ToPlace).perform();
ToPlace.sendKeys("mum");
List<WebElement> ToCities = driver.findElements(By.xpath("//ul[#role='listbox']//li/div[1]/div[2]"));
for (WebElement To : ToCities)
{
if (To.getText().contains("BOM")) {
try {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", To);
} catch (StaleElementReferenceException e) {
ToCities = driver.findElements(By.xpath("//ul[#role='listbox']//li/div[1]/div[2]"));
To.click();
}
List<WebElement> Radiobutton = driver
.findElements(By.xpath("//ul[#class='specialFareNew']/li/div[2]/p"));
for (WebElement Radio : Radiobutton) {
if (Radio.getText().contains("Armed Forces Fares")) {
Radio.click();
System.out.println("got the expected output");
break;
}
}
}
}
}
}
Related
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class AutoSuggestiveDropdown {
public static void main (String[] args) throws Exception {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Users\\HP\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://rahulshettyacademy.com/dropdownsPractise/");
driver.findElement(By.id("autosuggest")).sendKeys("ind");
Thread.sleep(3000L);
List<WebElement> options = driver.findElement(By.cssSelector("li[class='ui-menu-item'] a")); //Error
for(WebElement option : options) {
if(option.getText().equalsIgnoreCase("India")) {
option.click();
break;
}
}
}
}
You used 'findElement' in 'driver.findElement(By.cssSelector("li[class='ui-menu-item'] a"))'
You have to use 'findElements' in 'driver.findElements(By.cssSelector("li[class='ui-menu-item'] a"));'
import static org.junit.Assert.;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.After;
import org.junit.Before;
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.support.ui.Select;
public class excel {
WebDriver driver;
#Before public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\IVS Files\Selenium\Drivers\chromedriver v2.43\chromedriver.exe"");
driver.get("http://10.82.180.36/Common/Login.aspx");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5000,TimeUnit.MILLISECOND);
}
#After public void tearDown() throws Exception {
driver.close();
}
#Test public void test() throws
IOException, InterruptedException {
driver.findElement(By.id("body_txtUserID")).sendKeys("donhere");
driver.findElement(By.id("body_txtPassword")).
sendKeys("don#123");
driver.findElement(By.xpath("//[#id="body_btnLogin "]")).click();
driver.findElement(By.id("GeneralTabMenu_pnlCustomer_TopMenu")).click();
String path ="https://infosystechnologies-my.sharepoint.com/personal/doddi_suvarna_ad_infosys_com/Documents/Book1.xlsx";
FileInputStream file = new FileInputStream(path);
XSSFWorkbook book = new XSSFWorkbook(file);
XSSFSheet sheet1 = book.getSheetAt(0);
int rowcount = sheet1.getFirstRowNum();
System.out.println(rowcount);
for (int i = 0; i <= sheet1.getLastRowNum(); i++) {
double loanamount =sheet1.getRow(i).getCell(0).getNumericCellValue();
int month =(int) sheet1.getRow(i).getCell(1).
getNumericCellValue();
String la = String.valueOf(loanamount);
String m = String.valueOf(month);
Thread.sleep(5000);
WebElement name =driver.findElement(By.id("body_cph_Loans_ddlLoanName"));
Select name1 = new Select(name);
name1.selectByIndex(1);
Thread.sleep(5000);
driver.findElement(By.id("body_cph_Loans_txtReqLoanAmount")).sendKeys(la);
driver.findElement(By.id("body_cph_Loans_txtNoOfEMI")).sendKeys(m);
driver.findElement(By.id("body_cph_Loans_btnViewEMI")).click();
String abc =driver.findElement(By.id("body_cph_Loans_lblEMIAmountText")).getText();
driver.findElement(By.id("body_cph_Loans_btnReset")).click();
}
}
}
driver.get("http://10.82.180.36/Common/Login.aspx");
driver = new ChromeDriver();
You should first create object and then launch url...
driver = new ChromeDriver();
driver.get("http://10.82.180.36/Common/Login.aspx");
This is the baseclass.
package utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;
public class BaseClass {
public static WebDriver driver;
public WebDriverWait wait;
public static Properties prop;
FileInputStream fis;
static String browserName;
String currentDir = System.getProperty("user.dir");
public BaseClass()
{
prop=new Properties();
try {
fis = new FileInputStream(currentDir + "/src/test/java/config/data.properties");
} catch (FileNotFoundException e1) {
}
try {
prop.load(fis);
} catch (IOException e) {
}
}
public static void initialization()
{
browserName = prop.getProperty("browser");
if (browserName.equalsIgnoreCase("Chrome"))
{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
else if(browserName.contains("Firefox"))
{
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
else
{
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.get(prop.getProperty("url"));
}
}
This is login page
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import utils.BaseClass;
public class LoginPage extends BaseClass {
WebDriver driver;
public LoginPage(WebDriver ldriver)
{
this.driver= ldriver;
wait = new WebDriverWait(driver, 90);
PageFactory.initElements(driver, this);
}
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[1]//parent::div")
WebElement radioAccount;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[2]//parent::div")
WebElement radioVcNumber;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[3]//parent::div")
WebElement macId;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[4]//parent::div")
WebElement vSc;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[5]//parent::div")
WebElement rMn;
#FindBy(how=How.XPATH,using="//*[#id='txt_InputVal']")
WebElement enterRmn;
#FindBy(how=How.XPATH, using="//*[#id='btnsubmit']")
WebElement buttonSubmit;
public void clickRadioButtons()
{
wait.until(ExpectedConditions.visibilityOf(radioAccount));
radioAccount.click();
radioVcNumber.click();
macId.click();
vSc.click();
rMn.click();
}
public void loginWithRmn(String num)
{
rMn.click();
wait.until(ExpectedConditions.visibilityOf(enterRmn));
enterRmn.sendKeys(num);
}
public void clickOnLoginButton()
{
buttonSubmit.click();
}
}
This is step definition of login page.
package stepDefs;
import Pages.LoginPage;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import utils.BaseClass;
public class LoginStepDef extends BaseClass{
LoginPage login;
String title;
#Given("^User has launched URL on browser$")
public void user_has_launched_URL_on_browser()
{
BaseClass.initialization();
System.out.println("Browser Launched");
login = new LoginPage(driver);
}
#Given("^User is able to select different account types$")
public void user_is_able_to_select_different_account_types()
{
login = new LoginPage(driver);
login.clickRadioButtons();
}
#When("^User enters tries to login with Mobile Number \"([^\"]*)\"$")
public void user_enters_tries_to_login_with_Mobile_Number(String arg1)
{
login.loginWithRmn(arg1);
}
#Then("^User is logged in$")
public void user_is_logged_in()
{
login.clickOnLoginButton();
}
#After()
public void tearDown()
{
System.out.println("Browser Closed");
driver.quit();
}
}
This is test runner.
package runners;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features= {"src/test/java/featureFiles"},
glue= {"stepDefs"},
monochrome=true,
dryRun=false,
plugin= {"pretty"}
)
public class TestRunnerLogin {
}
How can I implement Hooks ?
Hooks as a different class file(Hooks.java) so that I don't have to write invoke browser again and again for further pages.
I want Hooks.java as a separate class and not implemented in some step definition.
this is my HOOKS file. maybe this can help you:
public class Hooks {
public static WebDriver driver;
#Before
public void startTest(Scenario scenario) {
System.setProperty("webdriver.chrome.driver", "src/test/resources/mac/chromedriver");
driver = new ChromeDriver();
driver.get("http://google.com");
}
#After
public void tearDown(Scenario scenario) {
Helper.screenshot(scenario);
driver.close();
}
public static WebDriver getDriver() {
return driver;
}
}
and follow how to use:
public class LoginSteps {
private LoginPage loginPage = new LoginPage(Hooks.getDriver());
#When("something")
public void signCheck() {
Assert.assertTrue("Login", homePage.checkPage());
}
}
package day2practice;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeSuite;
public class day2 {
ChromeDriver driver = new ChromeDriver();
#BeforeMethod
public void beforeMethod() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Ashok\\Desktop\\chromedriver.exe");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.navigate().to("http://live.guru99.com");
}
#Test
public void f() {
String actual = driver.getTitle();
String expected = "THIS IS DEMO SITE";
Assert.assertEquals(actual, expected, "page title is same");
}
#AfterMethod
public void close() {
driver.quit();
}
}
Don't instantiate ChromeDriver class before assigning the path to chromedriver.exe. Moved the instantiation code to beforeMethod.
try the following code:
package day2practice;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class day2 {
ChromeDriver driver;
#BeforeMethod
public void beforeMethod() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Ashok\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.navigate().to("http://live.guru99.com");
}
#Test
public void f() {
String actual = driver.getTitle();
String expected = "THIS IS DEMO SITE";
Assert.assertEquals(actual, expected, "page title is same");
}
#AfterMethod
public void close() {
driver.quit();
}
}
I'm trying to run a piece of code that I found online to run JUnit test in parallel but the only thing I've modified is the URL to hit my local host. Problem is I'm constantly getting the following error and even though I've setup selenium grid many times and know how to set paths etc. I don't know how to fix this one.
org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.ie.driver system property; for more information, see http://code.google.com/p/selenium/wiki/InternetExplorerDriver.
here's the code
package AutomationFrameWork;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;
public class Parallelized extends Parameterized {
private static class ThreadPoolScheduler implements RunnerScheduler {
private ExecutorService executor;
public ThreadPoolScheduler() {
String threads = System.getProperty("junit.parallel.threads", "16");
int numThreads = Integer.parseInt(threads);
executor = Executors.newFixedThreadPool(numThreads);
}
#Override
public void finished() {
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException exc) {
throw new RuntimeException(exc);
}
}
#Override
public void schedule(Runnable childStatement) {
executor.submit(childStatement);
}
}
public Parallelized(Class<?> klass) throws Throwable {
super(klass);
setScheduler(new ThreadPoolScheduler());
}
}
package AutomationFrameWork;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
#RunWith(Parallelized.class)
public class JUnitParallel {
private String platform;
private String browserName;
private String browserVersion;
private WebDriver driver;
#Parameterized.Parameters
public static LinkedList<String[]> getEnvironments() throws Exception {
LinkedList<String[]> env = new LinkedList<String[]>();
env.add(new String[]{Platform.WINDOWS.toString(), "chrome", "27"});
env.add(new String[]{Platform.WINDOWS.toString(),"firefox","20"});
env.add(new String[]{Platform.WINDOWS.toString(),"ie","11"});
env.add(new String[]{Platform.WINDOWS.toString(),"safari","5.1.7"});
//add more browsers here
return env;
}
public JUnitParallel(String platform, String browserName, String browserVersion) {
this.platform = platform;
this.browserName = browserName;
this.browserVersion = browserVersion;
}
#Before
public void setUp() throws Exception {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability("platform", platform);
capability.setCapability("browser", browserName);
capability.setCapability("browserVersion", browserVersion);
capability.setCapability("build", "JUnit-Parallel");
capability.setCapability("InternetExplorerDriverServer.IE_ENSURE_CLEAN_SESSION",true);
System.setProperty("webdriver.ie.driver",
"C:\\Users\\path to driver\\IEDriverServer.exe");
driver = new RemoteWebDriver(
new URL("http://localhost:7777".concat("/wd/hub")),
capability
);
}
#Test
public void testSimple() throws Exception {
driver.get("http://www.google.com");
String title = driver.getTitle();
System.out.println("Page title is: " + title);
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("BrowserStack");
element.submit();
driver = new Augmenter().augment(driver);
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(srcFile, new File("Screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}