Selenium xpath getting changed during run time - selenium

Scenario - Valid login to www.homeshop18.com and then from the Digital Menu select "Samsung".
The results are displayed and now I need to choose another brand - Micromax from the Brand section (displayed at the left side of the page)
which requires scrolling and selecting Micromax.
Issue:
Though the xpath of Micromax is correct which is //*[#id='filter_1Option_12']//div[#class='ez-checkbox'] but I see during run time of the script - some other brand is getting selected instead of micromax.
Kindly advise.
//Class for valid login to www.homeshop18.com
public class HomeShop_Login_Test
{
#FindBy(xpath="//a[#id='signInHeaderLink']") WebElement SignIn_Link;
#FindBy(xpath=".//input[#id='emailId']") WebElement Email;
#FindBy(xpath=".//input[#id='existing_user_radio']") WebElement Existing_User_Radio;
#FindBy(xpath=".//input[#id='new_user_radio']") WebElement New_User_Radio;
#FindBy(xpath=".//input[#id='password']") WebElement Password;
#FindBy(xpath=".//a[#id='signin']") WebElement SignIn_Button;
#FindBy(xpath="//a[#title='Close']") WebElement Close_Home;
public void Login_Valid()
{
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement SignIn_Link = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[#id='signInHeaderLink']")));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click()", SignIn_Link);
Email.sendKeys("xxx#gmail.com");
boolean selected;
selected = New_User_Radio.isSelected();
if(selected)
{
Existing_User_Radio.click();
}
Password.sendKeys("xxx");
SignIn_Button.click();
}
//Class to choose Samsung from Digital menu
public class Browse_Samsung_Mobile
{
#FindBy(xpath="//*[#id='CategoryMenu1']//a[text()='Digital']") WebElement Digital_Menu;
#FindBy(xpath="//*[#id='CategoryMenu1']//a[#title='Samsung']") WebElement Samsung_SubMenu;
#FindBy(xpath="//*[#id='filter_1Option_19']//span[#class='selected_filter_img']") WebElement Micromax;
public void Browse_Samsung()
{
WebDriverWait wait = new WebDriverWait(driver, 30);
Actions act = new Actions(driver);
act.moveToElement(Digital_Menu).perform();
act.click(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='CategoryMenu1']//a[#title='Samsung']")))).build().perform();
//WebElement Micromax = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id='filter_1Option_12']//span[#class='selected_filter_img']")));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click()", Micromax);
}
}
//class to call above two classes
public class Validate_Browse_Samsung_Mobile
{
WebDriver driver;
#Test
public void Validate_Browse()
{
driver = BrowserFactory.getBrowser("Firefox");
driver.get(DataProviderFactory.getConfig().getURL());
HomeShop_Login_Test login = PageFactory.initElements(driver, HomeShop_Login_Test.class);
login.Login_Valid();
Browse_Samsung_Mobile browse = PageFactory.initElements(driver, Browse_Samsung_Mobile.class);
browse.Browse_Samsung();
}
}

You should try with their name using title attribute as below :-
WebElement micromax = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("a[title ~= "Micromax"] input")));

You should use following XPath to choose proper check-box:
//a[#title="GSM Mobile Phones - Micromax"]/div/input

Related

The button in date picker is getting clicked more than the number of clicks needed [duplicate]

I am trying to select a "Depart date" as of 31st october 2018 from the calender https://spicejet.com/ But I am getting error "unknown error: Element is not clickable at point (832, 242). Other element would receive the click: ..." Please help me out. Here is my code getting such exception:
public class bookflight extends Thread {
UtilityMethods utilObj= new UtilityMethods();
#Test
public void SighnUp() throws IOException
{
utilObj.getdriver().get("https://spicejet.com");
utilObj.getdriver().manage().window().maximize();
utilObj.getdriver().findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
utilObj.getdriver().findElement(By.xpath("//a[contains(text(),'Guwahati (GAU)')]")).click();
utilObj.getdriver().findElement(By.xpath("//a[contains(text(),'Goa (GOI)')]")).click();
utilObj.getdriver().findElement(By.className("ui-datepicker-trigger")).click();
utilObj.getdriver().findElement(By.xpath("//div[#class='ui-datepicker-group ui-datepicker-group-first'])/parent:://table[#class='ui-datepicker-calendar']following-sibling::./a/contains(text(),'31')")).click();
}
}
To select From (e.g. Guwahati(GAU)), To (e.g. Goa(GOI)) destination and DEPART DATE as 31/10 within the url https://spicejet.com/ you need to induce WebDriverWait for the desired element to be clickable and you can use the following solution:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class spicejet_login {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://spicejet.com");
new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#id='ctl00_mainContent_ddl_originStation1_CTXT']"))).click();
driver.findElement(By.xpath("//div[#id='glsctl00_mainContent_ddl_originStation1_CTNR']//table[#id='citydropdown']//li/a[#value='GAU']")).click();
driver.findElement(By.xpath("//div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//table[#id='citydropdown']//li/a[#value='GOI']")).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//table[#class='ui-datepicker-calendar']//tr//a[contains(#class,'ui-state-default') and contains(.,'31')]"))).click();
}
}
Browser Snapshot:
There is lots of different factors which results into this exception,
i like to suggest you to try putting some wait.
WebDriverWait wait = new WebDriverWait(utilObj.getdriver(), 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("ctl00_mainContent_ddl_originStation1_CTXT")));
then try clicking element,
utilObj.getdriver().findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
You can click on element by Action class, based on Exception type:
Actions action = new Actions(driver);
action.moveToElement(WebElement to click).click().perform();
Updated answer to click next date.
//div[contains(#class, 'ui-datepicker-group-first')]//td[#data-month='9' and #data-year='2018']/a[.=31]
You can modify the above XPATH to select date based on YEAR/MONTH/DATE. for more XPath creation go-through my answers.
var path ="//div[contains(#class, 'ui-datepicker-group-first')]//td[#data-month='9' and #data-year='2018']/a[.=31]";
var elem = document.evaluate(path, window.document, null, 9, null ).singleNodeValue;
console.log( elem );
elem.click();
When you enter FROM and TO data, then DEPART DATE field get auto selected. So, just you need to select the first data using javascript.
FROM « //div[#id='ctl00_mainContent_ddl_originStation1_CTNR']//a[#text='Guwahati (GAU)']
TO « //div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[#text='Goa (GOI)']
DEPART DATE «
//div[contains(#class, 'ui-datepicker-group-first')]//a[contains(#class, 'ui-state-active')]
sample test program.
import io.github.yash777.driver.Browser;
import io.github.yash777.driver.Drivers;
import io.github.yash777.driver.WebDriverException;
public class SpiceJET {
static WebDriver driver;
static WebDriverWait explicitWait;
public static void main(String[] args) throws WebDriverException, IOException {
test();
}
public static void test() throws WebDriverException, IOException {
Drivers drivers = new Drivers();
String driverPath = drivers.getDriverPath(Browser.CHROME, 63, "");
System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
driver = new ChromeDriver( capabilities );
explicitWait = new WebDriverWait(driver, 10);
//Maximize browser window
driver.manage().window().maximize();
//Go to URL which you want to navigate
driver.get("https://spicejet.com/");
clickElement("//input[#id='ctl00_mainContent_ddl_originStation1_CTXT'][1]");
clickElement("//div[#id='ctl00_mainContent_ddl_originStation1_CTNR']//a[#text='Guwahati (GAU)']");
clickElement("//input[#id='ctl00_mainContent_ddl_destinationStation1_CTXT'][1]");
clickElement("//div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[#text='Goa (GOI)']");
clickUsingJavaScript("//div[contains(#class, 'ui-datepicker-group-first')]//a[contains(#class, 'ui-state-active')]");
}
}
public static void clickElement(String locator) {
By findBy = By.xpath( locator );
WebElement element = explicitWait.until(ExpectedConditions.elementToBeClickable( findBy ));
element.click();
}
public static void clickUsingJavaScript( String locator ) {
StringBuffer click = new StringBuffer();
click.append("var elem = document.evaluate(\""+locator+"\", window.document, null, 9, null ).singleNodeValue;");
click.append("elem.click();");
System.out.println("JavaScript Click.");
jse.executeScript( click.toString() );
}
For Automatic management of Selenium Driver Executable’s in run-time for Java use SeleniumWebDrivers
NOTE: If you are selecting DEPART DATE which got auto selected then selenium throws exception
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error:
Element <input type="text" readonly="readonly" id="ctl00_mainContent_view_date2" class="custom_date_pic required home-date-pick">
is not clickable at point (784, 241). Other element would receive the click: <span class="ui-datepicker-month">...</span>
I hope below code is helpful and handle departure and return date
public class SpicejetDropdowns1 {
public static void main(String[] args) throws InterruptedException
{ System.setProperty("webdriver.chrome.driver","E:\\ChromeDriver\\ChromeDriver2.46\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.spicejet.com/");
driver.manage().window().maximize();
System.out.println(driver.getTitle()); driver.findElement(By.cssSelector("#ctl00_mainContent_rbtnl_Trip_1")).click();
// OriginStation
driver.findElement(By.xpath(".//*[#id='ctl00_mainContent_ddl_originStation1_CTXT']")).click();
driver.findElement(By.cssSelector("a[value='DEL']")).click();
// Destination
driver.findElement(By.xpath(".//*[#id='ctl00_mainContent_ddl_destinationStation1_CTXT']")).click();
driver.findElement(By.xpath("(//a[#value='HYD'])[2]")).click();
Thread.sleep(3000); driver.findElement(By.xpath("//input[#id='ctl00_mainContent_view_date1']")).click();
if(driver.findElement(By.id("Div1")).getAttribute("style").contains("1"))
{
System.out.println("its enabled");
Assert.assertTrue(true);
}
else
{
Assert.assertTrue(false);
}
while(!driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText().contains("October"))
{
// driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click();
driver.findElement(By.xpath("//a[#class='ui-datepicker-next ui-corner-all']/span[#class='ui-icon ui-icon-circle-triangle-e']")).click();
System.out.println(driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText());
}
List<WebElement> dates= driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td"));
int count= dates.size();
for(int i=0; i<count; i++)
{
String txt = driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).getText();
if(txt.equalsIgnoreCase("28"))
{
driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).click();
System.out.println(txt);
break;
}
}
// Return Date Selection
Thread.sleep(3000); driver.findElement(By.xpath("//input[#id='ctl00_mainContent_view_date2']")).click();
while(!driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText().contains("October"))
{
// driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click();
driver.findElement(By.xpath("//a[#class='ui-datepicker-next ui-corner-all']/span[#class='ui-icon ui-icon-circle-triangle-e']")).click();
System.out.println(driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText());
}
List<WebElement> MDates= driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td"));
int Mcount= dates.size();
for(int i=0; i<Mcount; i++)
{
String txt = driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).getText();
if(txt.equalsIgnoreCase("31"))
{
driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).click();
System.out.println(txt);
break;
}
}
//Select Passengers
Thread.sleep(4000);
driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).click();
Thread.sleep(4000);
WebElement Adults = driver.findElement(By.xpath("//select[#id='ctl00_mainContent_ddl_Adult']")); Select adultsdrp = new Select(Adults);
adultsdrp.selectByValue("2");
WebElement childs = driver.findElement(By.xpath("//select[#id='ctl00_mainContent_ddl_Child']"));
Select childsdrp = new Select(childs);
childsdrp.selectByValue("2");
driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).click();
System.out.println(driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).getText());
//Static Currency Dropdown
WebElement Currency = driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency"));
Select currencydrp = new Select(Currency);
currencydrp.selectByValue("USD"); Assert.assertEquals(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")).getAttribute("value"), "USD"); System.out.println(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")).getAttribute("value"));
}
}

Automation Testing - Selenium WebDriver - Running Multiple Test Cases

I have got some problems with my automation testing.
I have nearly around 50 test cases in my Eclipse IDE. All test cases are in different classes. Also, I have got one BaseClass that contains #beforeclass and #afterclass. In #beforeclass, the browser opens, URL opens and website URL opens then it does login procedure.
Then my test cases work. All of them begin with #Test annotation.
I connect them with using TestNG suite.
Base Class:
My BaseClass.java class
MyBaseClass.java class
TestNg:
My Suite
Example of Test Case (Class):
My Example Test Case (Class)
Here is my question:
I want to use priority (like #Test (priority=1)) for these classes (test cases) for reducing the workforce. But when there is a problem with my codes; my automation test stops. I want to, it would continue besides the stop.
The second option is using TestNG. TestNG is ok but every case, the browser opens. How can I create a test like just opening one browser then run all test cases in that browser?
By the way here is my example test case for your imagine all picture:
-#beforeclass: open browser - open URL - login
#test1: go to products screen - click create a product - create a product with initial quantity - then click save button, it should be in the products screen again.
#test2: click create a product button again. - create a product without initial quantity - click save button, it should get an error. click the cancel button to continue the third #test
#test3: so on...
-#afterclass: close browser
I really appreciate for your help! Thank you!
Edit: I switched my codes as like this. Because I dont want to my automation opens a new browser over and over again. All my test cases relates with only one screen. (products) All I want is by ordering:
Initiate #BeforeSuite (open browser, URL..)
Initiate #BeforeClass(go to Products screen - because it is common screen for all cases)
Initiate #Test for Test Case 1
Initiate #AfterClass (go to Products screen again for a connection
with test case 2
Initiate #Test for Test Case 2
My Test NG class:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="AllTests" verbose="10" >
<test name="prcr1.1" >
<classes>
<class name="com.example.product.prcr1dot1" />
</classes>
</test>
<test name="prcr1.2" >
<classes>
<class name="com.example.product.prcr1dot2" />
</classes>
</test>
</suite>
My Base Class:
public class BaseClass {
protected WebDriver driver;
#BeforeSuite
public void openMyexample() throws InterruptedException {
System.out.println("Initiate LoginTest Test...");
driver = utilities.DriverFactory.open("chrome");
driver.manage().window().maximize();
driver.get("https://mystage.example.com/en/public/login/?isTestAutomationLive=true");
System.out.println("example Page Has Been Opened..");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable((By.name("email"))));
// Enter Username Section
WebElement username = driver.findElement(By.name("email"));
username.sendKeys("automationproducts4#example.com");
Thread.sleep(1000);
wait.until(ExpectedConditions.elementToBeClickable((By.name("password"))));
// Enter Password Section
WebElement password = driver.findElement(By.name("password"));
password.sendKeys("Test*01");
Thread.sleep(1000);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//form[#id='frmLogin']/button"))));
// Click Login Button
WebElement logInButton = driver.findElement(By.xpath("//form[#id='frmLogin']/button"));
logInButton.click();
// PAGE LOADER
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//span[contains(.,'×')]"))));
Thread.sleep(1000);
// Integration Message Function WebElement - Option 1: WebElement
WebElement popupCancelButton = driver.findElement(By.xpath("//span[contains(.,'×')]"));
popupCancelButton.click();
Thread.sleep(3000);
}
#BeforeClass
public void openProducts() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 20);
// From Dashboard Section to Product Section
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//a[contains(text(),'Products')]"))));
WebElement productButton = driver.findElement(By.xpath("//a[contains(text(),'Products')]"));
productButton.click();
Thread.sleep(4000);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//button[contains(.,'Create Product')]"))));
WebElement createProductButton = driver.findElement(By.xpath("//button[contains(.,'Create Product')]"));
createProductButton.click();
Thread.sleep(4000);
}
#AfterClass
public void closeProducts() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//a[contains(text(),'Products')]"))));
WebElement productButton = driver.findElement(By.xpath("//a[contains(text(),'Products')]"));
productButton.click();
Thread.sleep(4000);
}
#AfterSuite
public void closeMyexample() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 60);
Thread.sleep(4000);
// Sign Out Thread.sleep(5000);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//div[2]/i"))));
WebElement logoutScrollDownButton = driver.findElement(By.xpath("//div[2]/i"));
logoutScrollDownButton.click();
Thread.sleep(3000);
WebElement signoutButton = driver.findElement(By.xpath("//a[contains(.,'Sign Out')]"));
signoutButton.click();
// Close Browser
System.out.println("Your Test Has Been Ended Successfully.");
Thread.sleep(1000);
System.out.println("Your Test is going to Close..");
driver.quit();
}
// Sleep Function
private void sleep(long m) {
try {
Thread.sleep(m);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My Test Case 1:
package com.example.product;
import utilities.BaseClass;
//Test Case 1: PRCR - 1.1
//Creating a new product with a unique SKU
public class prcr1dot1 extends BaseClass {
#Test
public void prcr1dot1() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable((By.name("sku"))));
String uuid = UUID.randomUUID().toString();
driver.findElement(By.name("sku")).sendKeys(uuid);
driver.findElement(By.name("name")).sendKeys(uuid);
WebElement packType = driver
.findElement(By.xpath("//kendo-dropdownlist[#id='packTypeName']//span[#class='k-input']"));
packType.click();
wait.until(ExpectedConditions.elementToBeClickable((By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))));
driver.findElement(By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))
.sendKeys(uuid);
wait.until(ExpectedConditions.elementToBeClickable((By.id("btnCreateProductPackTypeName"))));
WebElement createPackType = driver.findElement(By.id("btnCreateProductPackTypeName"));
createPackType.click();
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//button[contains(.,'SAVE')]"))));
WebElement productSaveButton = driver.findElement(By.xpath("//button[contains(.,'SAVE')]"));
productSaveButton.click();
Thread.sleep(8000);
}
}
My Test Case 2:
import utilities.BaseClass;
public class prcr1dot2 extends BaseClass {
// Test Case 2: PRCR - 1.2
// Creating a new product with the used SKU
#Test
public void prcr1dot2() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable((By.name("sku"))));
driver.findElement(By.name("sku")).sendKeys("SKU08");
String uuid = UUID.randomUUID().toString();
driver.findElement(By.name("name")).sendKeys(uuid);
WebElement packType = driver
.findElement(By.xpath("//kendo-dropdownlist[#id='packTypeName']//span[#class='k-input']"));
packType.click();
wait.until(ExpectedConditions.elementToBeClickable((By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))));
driver.findElement(By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))
.sendKeys(uuid);
wait.until(ExpectedConditions.elementToBeClickable((By.id("btnCreateProductPackTypeName"))));
WebElement createPackType = driver.findElement(By.id("btnCreateProductPackTypeName"));
createPackType.click();
JavascriptExecutor jsx = (JavascriptExecutor) driver;
jsx.executeScript("window.scrollBy(0,450)", "");
WebElement productSaveButton = driver.findElement(By.xpath("//button[contains(.,'SAVE')]"));
productSaveButton.click();
Thread.sleep(5000);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//button[contains(.,'Create Product')]"))));
WebElement createProductButton2 = driver.findElement(By.xpath("//button[contains(.,'Create Product')]"));
createProductButton2.click();
wait.until(ExpectedConditions.elementToBeClickable((By.name("sku"))));
driver.findElement(By.name("sku")).sendKeys("SKU08");
String uuid2 = UUID.randomUUID().toString();
driver.findElement(By.name("name")).sendKeys(uuid2);
WebElement packType2 = driver
.findElement(By.xpath("//kendo-dropdownlist[#id='packTypeName']//span[#class='k-input']"));
packType2.click();
wait.until(ExpectedConditions.elementToBeClickable((By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))));
String uuid3 = UUID.randomUUID().toString();
driver.findElement(By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))
.sendKeys(uuid3);
wait.until(ExpectedConditions.elementToBeClickable((By.id("btnCreateProductPackTypeName"))));
WebElement createPackType2 = driver.findElement(By.id("btnCreateProductPackTypeName"));
createPackType2.click();
/*
* WebElement productSaveButton2 =
* driver.findElement(By.xpath("//button[contains(.,'SAVE')]"));
* productSaveButton2.click(); Thread.sleep(5000); WebElement
* productCancelButton2 =
* driver.findElement(By.xpath("//button[contains(.,'CANCEL')]"));
* productCancelButton2.click(); Thread.sleep(2000);
* wait.until(ExpectedConditions.elementToBeClickable((By.xpath(
* "//button[contains(.,'YES')]")))); WebElement productCancelYesButton =
* driver.findElement(By.xpath("//button[contains(.,'YES')]"));
* productCancelYesButton.click();
*/
}
}
I am not sure it will solve your problem or not. But This idea works for me. Using this way you can run all the test case on same browser without opening multiple times.
Here I have three class
test1.java
test2.java
test2.java
And Mainclass.java
Here is test1.java
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class test1 {
#BeforeClass
public void before(){
}
#Test
public static void test(WebDriver driver){
driver.get("https://www.google.com");
}
#AfterMethod
public void after(){
}
}
Here is test2.java
package test;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
public class test2 {
#Test
public static void test(WebDriver driver){
driver.get("https://www.yahoo.com");
}
}
Here is mainclass.java file where I passed driver session to the test
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Mainclass {
public static void main(String[]args){
WebDriver driver;
driver=new ChromeDriver();
test1.test(driver);
test2.test(driver);
}
}
Now you need to run mainclass from testing.xml file.
From the main class you can open browser one time and passed driver to your all the test case so it will use browser window to run the test case.
I am not sure any other ideal idea is available or not but it will surely work for you

How to interact with webelement on popup while browser loader running?

I have an authentication popup before loading the website and while popup display on the webpage and a loader display running on the browser it means webpage not loaded completely.
And as per selenium if complete webpage not loaded initially, selenium not interact with elements
Need help on this.
Use following method with Java + Selenium :
public boolean isPageReady(WebDriver driver){
boolean readyStateComplete = false;
while (!readyStateComplete){
JavascriptExecutor executor = (JavascriptExecutor) driver;
readyStateComplete = executor.executeScript("return document.readyState") == "complete";
}
return readyStateComplete;
}
For C# + Selenium :
private void WaitUntilDocumentIsReady(TimeSpan timeout){
var javaScriptExecutor = WebDriver as IJavaScriptExecutor;
var wait = new WebDriverWait(WebDriver, timeout);
// Check if document is ready
Func<IWebDriver, bool> readyCondition = webDriver => javaScriptExecutor
.ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
wait.Until(readyCondition);
}
You can wait until the page is completely loaded via JavaScript.
private void WaitUntilLoaded()
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until((x) =>
{
return ((IJavaScriptExecutor)this.driver)
.ExecuteScript("return document.readyState").Equals("complete");
});
}
Another option is to wait for a specific element(s) to be visible on the page
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
By.XPath("some Xpath")));
Source here: https://www.automatetheplanet.com/advanced-webdriver-tips-tricks-part-1/

How to write a generalized web driver wait in Selenium

I am trying to write a generalized web driver wait to wait for elements to be clickable. But I found out online of Web Driver waits that are written specific to By.id or By.name.
Suppose Below are two WebElements
public WebElement accountNew() {
WebElement accountNew = driver.findElement(By.xpath("//input[#title='New']"));
waitForElementtobeClickable(accountNew);
return accountNew;
}
public WebElement accountName() {
WebElement accountName = driver.findElement(By.id("acc2"));
waitForElementtobeClickable(accountName);
return accountName;
}
Below is the generalized waitofrelementtobeclickable.
public static void waitForElementtobeClickable(WebElement element) {
try {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(element));
System.out.println("Got the element to be clickable within 10 seconds" + element);
} catch (Exception e) {
WebDriverWait wait1 = new WebDriverWait(driver, 20);
wait1.until(ExpectedConditions.elementToBeClickable(element));
System.out.println("Got the element to be clickable within 20 seconds" + element);
e.printStackTrace();
}
}
but it doesn't seem to work. Any suggestions on how only one generalized code can be written for either xpath, or id, or class or Css can be written?
The problem is not in your function, its in your driver.findElement as you try to locate the element before it exist in the DOM. You can use implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
This will wait up for 10 seconds for any element to exist in the DOM before when locating it.
Or locate your element using explicit wait
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#title='New']")));
This will wait up to 10 seconds for your element to be visible.
You can (and should) use both of course.
You can change your code to something like that
public static WebElement waitForElementtobeClickable(By by) {
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(by));
System.out.println("Got the element to be clickable within 10 seconds" + element);
return element;
}
public WebElement accountNew() {
WebElement accountNew = waitForElementtobeClickable(By.xpath("//input[#title='New']"));
return accountNew;
}
You send your By locator to waitForElementtobeClickable and use elementToBeClickable(By) instead of elementToBeClickable(WebElement), so you can use xpath, id, class etc.

Unable to control slider captcha jquery using Selenium Webdrive?

I want to record slider captcha given on our client site.
We have get this concept from other site named as http://www.fmylife.com/signup
This have slider captcha for registration
I have try to use selenium webdriver action builder
public class TestFmylife {
WebDriver driver;
Selenium selenium;
#BeforeMethod
public void startSelenium() {
driver = new FirefoxDriver();
selenium = new WebDriverBackedSelenium(driver, "http://www.fmylife.com/");
driver.manage().window().maximize();
}
#AfterMethod
public void stopSelenium() {
driver.close();
}
#Test
public void testFmylife() {
selenium.open("/");
selenium.click("link=Sign up");
selenium.waitForPageToLoad("30000");
selenium.type("name=login", "testfmylife");
selenium.type("name=pass", "123#fmylife");
selenium.type("name=passc", "123#fmylife");
selenium.type("name=mail", "testfmylife#gmail.com");
Point MyPoint= driver.findElement(By.xpath("//*[#id='bgSlider']")).getLocation();
WebElement someElement = driver.findElement(By.xpath("//*[#id='bgSlider']"));
System.out.println(MyPoint.x+"--------"+MyPoint.y);
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement).moveByOffset(MyPoint.x,(MyPoint.y + 100)).release().build();
dragAndDrop.perform();
selenium.click("css=div.form > div.ok > input[type=\"submit\"]");
}
}
But I can't move slider using this code
Help me to sort this out
I used the dragAndDropBy method of the Actions class (java.lang.Object
org.openqa.selenium.interactions.Actions) and moved the slider by 200 points horizontally . Please give the following code a try:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.fmylife.com/signup");
WebElement slider = driver.findElement(By.xpath(".//*[#id='Slider']"));
Actions builder = new Actions (driver);
builder.dragAndDropBy(slider, 200, 0).build().perform();
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement)
.moveToElement(otherElement)
.release(otherElement)
.build();
dragAndDrop.perform();
more can be found at - http://code.google.com/p/selenium/wiki/AdvancedUserInteractions
You can use locator as follows -
String xto=Integer.toString(LocatorTo.getLocation().x);
String yto=Integer.toString(LocatorTo.getLocation().y);
Working code-
WebDriver driver = new InternetExplorerDriver();
driver.get("http://jqueryui.com/demos/slider/");
//Identify WebElement
WebElement slider = driver.findElement(By.xpath("//div[#id='slider']/a"));
//Using Action Class
Actions move = new Actions(driver);
Action action = move.dragAndDropBy(slider, 30, 0).build();
action.perform();
driver.quit();
Source - https://gist.github.com/2497551
If your slider is like mine
with a "slider handle" (an <a/> tag as the box with the value "5ft 5") within a "slider track" (a <div> tag as the long black bar) then the following code will in C# will work to move the slider handle a percentage along the slider track.
public void SetSliderPercentage(string sliderHandleXpath, string sliderTrackXpath, int percentage)
{
var sliderHandle = driver.FindElement(By.XPath(sliderHandleXpath));
var sliderTrack = driver.FindElement(By.XPath(sliderTrackXpath));
var width = int.Parse(sliderTrack.GetCssValue("width").Replace("px", ""));
var dx = (int)(percentage / 100.0 * width);
new Actions(driver)
.DragAndDropToOffset(sliderHandle, dx, 0)
.Build()
.Perform();
}