I have created two sets of code contained in two seperate classes
Task Required: need to click on the 'Cash' button on the PH payment page.
Class one = simple class, simple code = code works and can click on the cash option.
Class two = setup contains page objects, framework uses different structure = code is unable to click on the cash option when reaching the payment page = 'org.openqa.selenium.StaleElementReferenceException: Element not found in the cache'
I have used the same locators within both classes but when uses the correct locator in '2' its unable to click on the 'radio' button; as listed above i get the listed error; i have tried to create bespoke methods; using loops etc and different locators but nothing works.
Working code and class:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class TestClass {
#Test
public void test() throws InterruptedException {
//System.setProperty("webdriver.chrome.driver", "C:\\Users\\GBruno\\Desktop\\masteringSelenium\\Framework\\src\\test\\resources\\chromedriver.exe");
// WebDriver driver = new ChromeDriver();
WebDriver driver = new FirefoxDriver();
driver.get("http://www.pizzahut.co.uk");
driver.manage().window().maximize();
//click pizza button
driver.findElement(By.cssSelector("div[id='page'] [href='/menu/pizza']")).click();
//select any pizza to start order
driver.findElement(By.cssSelector("div[class='col-xxs-8 col-xs-6 col-sm-8 col-md-7 col-lg-6'] *> button")).click();
//enter postcode and find hut
Thread.sleep(2000);
driver.findElement(By.cssSelector("#ajax-postcode-txt")).sendKeys("TS1 4AG");
driver.findElement(By.cssSelector(" #get-store-btn")).click();
//click start order button
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='store-collection-section']/div[2]/div[4]/div[4]/div/a")).click();
//add pizza
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='pizza-product-list']/div/div[1]/div/div[2]/div[2]/div[3]/div/form/button")).click();
//click mini basket
driver.findElement(By.xpath("html/body/nav/div/div/div[3]/div/div[1]/div[2]/span[3]")).click();
Thread.sleep(2000);
//click checkout
driver.findElement(By.xpath(".//*[#id='divBasket']/div[1]/div/div[2]/div[2]/a")).click();
Thread.sleep(2000);
//checkout guest & enter details
driver.findElement(By.xpath(".//*[#id='frmCheckout']/div[2]/div/div[1]/a")).click();
driver.findElement(By.xpath(".//*[#id='ddlTitleSelectBoxIt']")).click();
driver.findElement(By.linkText("Mr")).click();
driver.findElement(By.xpath(".//*[#id='FirstName']")).sendKeys("Tom");
driver.findElement(By.xpath(".//*[#id='LastName']")).sendKeys("Hanks");
driver.findElement(By.xpath(".//*[#id='EmailAddress']")).sendKeys("tom_hanks12344566#mail.com");
driver.findElement(By.xpath(".//*[#id='ConfirmEmailAddress']")).sendKeys("tom_hanks12344566#mail.com");
driver.findElement(By.xpath(".//*[#id='PhoneNumber']")).sendKeys("01234 5647890");
driver.findElement(By.xpath(".//*[#id='btnFindAddress']")).click();
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='ddlAddressesToChooseSelectBoxItArrowContainer']")).click();
driver.findElement(By.linkText("K F C 189-191 Linthorpe Road Middlesbrough TS14AG")).click();
driver.findElement(By.xpath(".//*[#id='btnContinue']")).click();
driver.findElement(By.xpath(".//*[#id='payment-methods']/div[1]/div/label/input")).click();
}
}
Code dosnt work:
public void selectPaymentTypeAndPayForOrder() throws Exception {
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='payment-methods']/div[1]/div/label/input")).click();
driver.findElement(By.cssSelector(" form[id='CheckoutForm'] input[data-paymentname='Cash']")).click();
The following code resolved the issue:
List<WebElement> iframes = driver.findElements(By.tagName("iframe"));
if(iframes.size() == 0) {
Assert.fail();
} else {
// Frames present
Assert.assertTrue(true);
}
Related
My myntra wishlist has 41 products, of which 19 are out of stock. I tried printing the names of the 'out of stock' products.
'out of stock' elements had a common class name using which I identified the product's name using xpath by traversing through parent and child nodes.
when i validated it in console, it gave the right response. It showed 19 products and when i hovered the mouse pointer it highlighted the out of stock products as expected. Works as expected when i debugged the code too.
But when i hit run, it printed only 7 products, size of the list was 7.
The page initially displays top 20 products and later displays the remaining as we scroll down. Out of the top 20, 7 are out of stock. Could this be a reason. If that is the case, how to handle this scroll event?
Here's the code snippet:
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;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class stockout {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait w =new WebDriverWait(driver,30);
driver.get(myntra login page);
//enter phone number driver.findElement(By.xpath(("//div[#class='signInContainer']/div[2]/div/input"))).sendKeys(phone number);
driver.findElement(By.cssSelector("div.submitBottomOption")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//div[#class='bottomeLink']/span")).click();
//enter password
driver.findElement(By.xpath("//input[#type='password']")).sendKeys(password);
driver.findElement(By.cssSelector("button.btn.primary.lg.block.submitButton")).click();
Thread.sleep(4000);
//open wishlist
driver.findElement(By.cssSelector("span.myntraweb-sprite.desktop-iconWishlist.sprites-headerWishlist")).click();
//add out of stock elements to a list
List<WebElement> outofstock = driver.findElements(By.xpath("//img[#class='itemcard-outOfStockItemImage itemcard-itemImage']/parent::picture/parent::a/parent::div/parent::div/div[2]/div/p[1]"));
//explicit wait
w.until(ExpectedConditions.visibilityOfAllElements(outofstock));
System.out.println(outofstock.size());
System.out.println("Items out of stock:");
for (WebElement product: outofstock)
{ System.out.println(product.getText());
}
}
}
Found the solution on the net, but wondering if there's any simpler way to do this. Suggestions are welcomed.
I added this piece of code to scroll down and it worked:
try {
Object lastHeight = ((JavascriptExecutor) driver).executeScript("return document.body.scrollHeight");
while (true) {
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight);");
Thread.sleep(2000);
Object newHeight = ((JavascriptExecutor) driver).executeScript("return document.body.scrollHeight");
if (newHeight.equals(lastHeight)) {
break;
}
lastHeight = newHeight;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
You can use the following code if you are expecting a specific number of elements to be present.
new WebDriverWait(driver,10).until(ExpectedConditions.numberOfElementsToBe(By by, 19));
I am trying to learn selenium by testing them on different websites. In this process, I am trying to work with Flipkart website. In this, I would like to give puma is search bar and trying to click one of the resultant items. But I am not able to do that using below-mentioned code. Could anyone help in solving it?
Secondly, If we click on any item, it is redirected to new-tab. How to access the new-tab elements using the same script?
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AutomationTesting {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","/Users/xxxx/eclipse-workspace/seleniumTesting/lib/geckoDriver/geckodriver");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.de");
driver.findElement(By.id("lst-ib")).sendKeys("flipkart");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Flipkart")));
driver.findElement(By.partialLinkText("Flipkart")).click();
driver.findElement(By.cssSelector("._3Njdz7 [class = '_2AkmmA _29YdH8']")).click();
driver.findElement(By.xpath("//input[#class = 'LM6RPg']")).click();
driver.findElement(By.xpath("//input[#class = 'LM6RPg']")).sendKeys("Puma");
driver.findElement(By.xpath("//button[#class = 'vh79eN']")).click();
driver.findElement(By.xpath("//a[#title='Puma Men Black Wallet' and #class= '_1Nyybr _30XEf0']")).click();
}
}
You need to use the window switchTo feature.
String mainWindowHandle = driver.getWindowHandle();
ArrayList<String> wins = driver.getWindowHandles();
// You can use a for loop here, or get the assumed second window directly
driver.switchTo().window(wins.get(1));
// Test some things, then switch back
driver.close();
driver.switchTo().window(mainWindowHandle);
See http://www.seleniumhq.org/docs/03_webdriver.jsp#moving-between-windows-and-frames
You will have to inspect that entire frame. I would suggest instead of customising xpaths on your own try firebug and firepath add on of Firefox for getting xpath of entire elements. Inspect the entire frame within which the results are getting displayed then save it in some variable like below one:
List<WebElements> searchResults;
searchResults=driver.findElements(By.xpath("Your xpath"));
Then access elements of this list using index and then you can perform .click() action on the same. More on this link for capturing xpath using firebug and firepath
Question 1: During the execution of the last line in the above code I am getting the following error. Unable to locate element: //a[#title='Puma Men Black Wallet' and #class= '_1Nyybr _30XEf0']
--> Due to Lazy loading webelement not present in dom at the time when you are hiting click event on it. So to over come this you need to make the webElement on view and then hit the click event.
Please refer below code:-
driver.get("https://www.google.de");
driver.findElement(By.id("lst-ib")).sendKeys("flipkart");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
WebDriverWait wait = new WebDriverWait(driver,60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Flipkart")));
driver.findElement(By.partialLinkText("Flipkart")).click();
try{
driver.findElement(By.cssSelector("._3Njdz7 [class = '_2AkmmA _29YdH8']")).click();
}catch(Exception e){
System.out.println("No division");
}
driver.findElement(By.xpath("//input[#class = 'LM6RPg']")).click();
driver.findElement(By.xpath("//input[#class = 'LM6RPg']")).sendKeys("Puma");
driver.findElement(By.xpath("//button[#class = 'vh79eN']")).click();
// Thread.sleep(3000);
wait.until(ExpectedConditions.visibilityOf( driver.findElement(By.xpath("//a[#title='Puma Men Black Wallet']"))));
// getting element into view
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", driver.findElement(By.xpath("//*[#alt='Puma Men Black Wallet']")));
Thread.sleep(2000);
driver.findElement(By.xpath("//*[#alt='Puma Men Black Wallet']")).click();
Question 2: If that last command works then it is redirected to the new tab. So how to access the elements from the new-tab?
--> As suggested be #Damian Jansen add that code after last click event.
String mainWindowHandle = driver.getWindowHandle();
ArrayList<String> wins = driver.getWindowHandles();
for(String win : wins ){
driver.switchTo().window(win);
// other operation
System.out.println(driver.getTitle());
}
// back to old window
driver.switchTo().window(mainWindowHandle);
System.out.println(driver.getTitle());
Hope this help you :)
Use this code to reach upto puma and then select the option use below code
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver","G:\\java programme\\SendkeysExample\\lib\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.google.com");
driver.findElement(By.id("lst-ib")).sendKeys("flipkart");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
driver.findElement(By.linkText("Flipkart")).click();
driver.findElement(By.className("LM6RPg")).sendKeys("Puma");
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_DOWN);
rb.keyPress(KeyEvent.VK_DOWN);
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_DOWN);
rb.keyRelease(KeyEvent.VK_DOWN);
rb.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
/*driver.findElement(By.xpath(".//*[#id='container']/div/header/div[1]/div/div/div/div[1]/form/ul/li[2]/a"));
driver.findElement(By.className("icon-add-circle"))*/;
driver.close();
}
}
The website I am trying to automate is betting website and I have a scenario to automate a horse betting.
I am using selenium 3.0 with Java
From the site I am able to travel to horse race but unable to select Tomorrow and select the race. I tried using xpath, class and other methods but unable to click on these button.
website is
https://www.williamhill.com.au/
1 step. go to the above url
2. Select horse racing from top left corner or navigate to url (https://www.williamhill.com.au/racing?event=horseracing)
3.Click on Tomorrow I am unable to do this
4. Select on particular race from the table (unable to this too)
package automationFramework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class horseRacing {
public static void main(String[] args) throws Exception {
String exePath = "D:\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", exePath);
WebDriver driver = new ChromeDriver();
//Launch the Online Store Website
driver.get("https://www.williamhill.com.au/");
Thread.sleep(5);
driver.manage().window().maximize();
String Title = driver.getTitle();
System.out.println(Title);
driver.findElement(By.className("MenuItem_text_N8V")).click();
Thread.sleep(25);
// driver.findElement(By.className("RaceGrid_raceTile_imG RaceGrid_raceDisabled_Q0m")).click();
driver.findElement(By.xpath("//*[#id='app']/div/div[4]/div/div/div/div[2]/div[1]/div/div[2]/div[2]/div[2]")).click();
// Print a Log In message to the screen
System.out.println("Successfully opened the website www.Store.Demoqa.com");
//Wait for 5 Sec
Thread.sleep(5);
// Close the driver
// driver.quit();
}
}
I tried to click "TOMORROW" and succeeded.
package test;
import org.openqa.selenium.By;
import org.junit.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class NavigateToAUrl {
#Test
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.williamhill.com.au/racing?event=horseracing");
driver.findElement(By.xpath(".//*[#id='app']/div/div[4]/div/div/div/div[2]/div[1]/div/div[2]/div[2]/div[2]")).click();
}
}
Dot(.) is missing in your code driver.findElement(By.xpath("//*[#id='app']/div/div[4]/div/div/div/div[2]/div[1]/div/div[2]/div[2]/div[2]")).click();
(Before //*[#id~)
I'm trying to simulate a few clicks for my new program but I'm stuck on the last thing!
I've managed to make selenium open the page and click on the checkbox which shows a rectangle popup with 9 buttons inside it. The only problem is clicking the buttons inside the pop up! I've checked the xpath a few times but Selenium says "No such element"
Here is my code:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class test {
static WebDriver driver;
public static void main(String[] args) {
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
driver = new FirefoxDriver(myprofile);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.runelocus.com/top-rsps-list/vote-1858-GrinderScape%20-%20New%20Website%20and%20Great%20Updates!/");
driver.switchTo().frame(1);
driver.findElement(By.xpath("//*[#id='recaptcha-anchor']/div[5]")).click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.findElement(By.cssSelector("#rc-imageselect-target > table > tbody > tr:nth-child(1) > td:nth-child(2)")).click();
}
}
Link to the problem: http://www.runelocus.com/top-rsps-list/vote-1858-GrinderScape%20-%20New%20Website%20and%20Great%20Updates!/
EDIT:
It creates the new elements after you click the checkbox. How would I click them?
Element you are trying to click is in iframe. We need to switch explicitly to that iframe for selenium to locate that element. Below code worked for me. (Please format Xpath in better readable format.)
driver.get("http://www.runelocus.com/top-rsps-list/vote-1858-GrinderScape%20-%20New%20Website%20and%20Great%20Updates!/");
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
WebElement iframeSwitch = driver.findElement(By.xpath("/html/body/section/div/div/section/div/article/div/div[2]/form/table/tbody/tr/td[1]/div/div/div/iframe"));
driver.switchTo().frame(iframeSwitch);
System.out.println("Switched");
driver.findElement(By.cssSelector("div[class=recaptcha-checkbox-checkmark]")).click();
i have written a basic test using selenium. The test is failing as the selenium unable to select the item from drop down list.
My select statement is not getting executed. Also i have include this select statement within iframe as this falls under it.
Can you please let me know what is the issue with my select statement.
Here is my code for southwest website:
package Default;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
//import org.openqa.selenium.firefox.FirefoxDriver;
public class FirstWDWithoutRecording {
#Test
public void SouthWestSignUp() throws InterruptedException
{
//Open the FF/Chrome browser
//FirefoxDriver oBrw = new FirefoxDriver();
ChromeDriver oBrw = new ChromeDriver();
//Maximize Browser
oBrw.manage().window().maximize();
//Open/Launch www.southwest.com
System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe");
oBrw.get("http://www.southwest.com/");
//Click on Sign up and Save
//Recognising
oBrw.findElement(By.linkText("Sign up")).click();
//oBrw.get("http://www.southwest.com/html/email/click_n_save_signup.html?clk=GFOOTER-CNS-ENROLL");
Thread.sleep(5000);
//Enter First Name
oBrw.switchTo().frame(0); //'0' as it is the only iframe on the page, the value is the index of all iframes on the page
//do your login actions
oBrw.findElement(By.xpath("//input[#id='FIRST_NAME']")).clear();
oBrw.findElement(By.xpath("//input[#id='FIRST_NAME']")).sendKeys("abc");
//Enter Last Name
oBrw.findElement(By.id("LAST_NAME")).clear();
oBrw.findElement(By.id("LAST_NAME")).sendKeys("Kish123");
//Enter Email ID
oBrw.findElement(By.id("EMAIL")).clear();
oBrw.findElement(By.id("EMAIL")).sendKeys("abc#Kish123.com");
//Selecting Home Airport
Select uiHomeAp = new Select(oBrw.findElement(By.id("HOME_AIRPORT")));
uiHomeAp.deselectByVisibleText("Atlanta, GA - ATL");
//Accepting Conditions
oBrw.findElement(By.id("IAN")).click();
//Click Submit
oBrw.findElement(By.id("submit")).click();
//after return
oBrw.switchTo().defaultContent();
}
}
As #SiKing had stated, your issue is with your deselectByVisibleText(). You want selectByVisibleText().
uiHomeAp.selectByVisibleText("Atlanta, GA - ATL");
Also wanted to point out that it might be easier if you are just getting started, to check out the getting started with selenium framework. If you're using maven, you could do:
<dependency>
<groupId>io.ddavison</groupId>
<artifactId>getting-started-with-selenium-framework</artifactId>
<version>1.2</version>
</dependency>
then your test would look like this:
#Config(browser = Browser.CHROME, url="http://www.southwest.com/")
public class FirstWDWithoutRecording extends AutomationTest {
public void southWestSignUp() {
click(By.linkText("Sign up"))
.switchToFrame(0)
.setText("input#FIRST_NAME", "abc")
.setText("input#LAST_NAME", "Kish123")
.setText("input#EMAIL", "abc#Kish123.com")
.selectOptionByText("select#HOME_AIRPORT", "Atlanta, GA - ATL")
.check("#IAN") // check the terms and conditions
.click("#submit") // form submitted
.switchToDefaultContent()
;
}
}