There's a website with a div, containing 7 items, when one item is added to cart there is a new popup regarding continue shopping or checkout. Need to automate, Add all the 7 items one by one while clicking Continue shopping over the pop.
I tried this with nested For Loops, but looks like nested for loop variable "j" not incrementing.
Currently, for the first item, works as expected, but for the rest of the items, just the first loop's mouse hover action is performed.
Also please instruct if any better methods than my method, much appreciated.
Code:
import java.time.Duration;
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.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class DressShop {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:/Java with Lan/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.get("http://automationpractice.com/index.php");
List<WebElement> offers = driver.findElements(By.cssSelector("#homefeatured li"));
List<WebElement> addCarts = driver.findElements(By.xpath("//ul[#id='homefeatured']/li/div/div[2]/div[2]/a[1]"));
Actions a = new Actions(driver);
for (int i = 0; i < offers.size(); i++) {
WebElement offer = offers.get(i);
a.moveToElement(offer).build().perform();
for (int j = 0; j == i; j++) {
WebElement addCart = addCarts.get(j);
wait.until(ExpectedConditions.elementToBeClickable(addCart));
a.moveToElement(addCart).click().build().perform();
WebElement closePop = driver.findElement(By.xpath("//span[#title='Continue shopping']"));
wait.until(ExpectedConditions.elementToBeClickable(closePop));
a.moveToElement(closePop).click().build().perform();
}
}
}
}
You don't really need nested loop for this type of scenarios.
You can collect all the link
//ul[#id='homefeatured']//li
using this xpath, now iterate over the list and hover the mouse to each product and click on add to cart and then continue shopping.
Code:
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:/Java with Lan/chromedriver.exe");
WebDriver driver = new ChromeDriver();
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
driver.manage().window().maximize();
driver.get("http://automationpractice.com/index.php");
Actions action = new Actions(driver);
List<WebElement> allLinks = driver.findElements(By.xpath("//ul[#id='homefeatured']//li"));
for (WebElement link : allLinks) {
action.moveToElement(wait.until(ExpectedConditions.visibilityOf(link))).pause(3).build().perform();
WebElement addToCart = link.findElement(By.xpath(".//descendant::div[#class='right-block']//descendant::a[#title='Add to cart']"));
action.moveToElement(addToCart).pause(2).click().build().perform();
//wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//descendant::div[#class='right-block']//descendant::a[#title='Add to cart']")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[#title='Continue shopping']"))).click();
}
Related
With Selenium webdriver, I am trying search 'Selenium' in google search box, which provides auto suggestions of several texts. Then I am trying to click one particular text from auto suggestions list. It seems though, my Xpath is not working.
Below is the code I wrote:
package com.initial.selenium;
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 GoogleSearch {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Shahid\\eclipse-
workspace\\InitialSeleniumProject\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.findElement(By.xpath("//*[#name='q']")).sendKeys("selenium");
List < WebElement >
mylist=driver.findElements(By.xpath("//ul[#role='listbox']//li/descendant::div[#class='sbl1']/span"));
System.out.println(mylist.size());
for (int i = 0; i < mylist.size(); i++) {
System.out.println(mylist.get(i).getText());
if (mylist.get(i).getText().contains("Selenium Benefits")) {
mylist.get(i).click();
break;
}
}
}
Try this:
List<WebElement> options = new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath("//ul[#role='listbox']//li/descendant::span"), 0));
System.out.println("no. of suggestions:"+options.size());
for(int i=0;i<options.size();i++) {
System.out.println(options.get(i).getText());
}
In this case, the error you're getting (a null result) is because the ul element you're targeting doesn't contain any elements.
So, in this case, you're going to change your target. Instead of doing:
ul[#role='listbox']
Do
li[#role='presentation']
And that will result in
//li[#role='presentation']/descendant::div[#class='sbl1']/span
Which returns the span you're trying to get.
This question already has answers here:
Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click
(9 answers)
Closed 4 years ago.
package Roughpack;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class MyClass {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","D:\\Executabel\\geckodriver-v0.21.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 20);
driver.get("http://pro.tykitksa.com/");
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
List<WebElement> dropDownList = driver.findElements(By.id("user_event_city"));
System.out.println(dropDownList.size());
for (int i = 0; i < dropDownList.size(); i++) {
System.out.println(dropDownList.get(i).getText());
WebElement Dropdown = driver.findElement(By.id("user_event_city"));
Select select = new Select(Dropdown);
select.selectByIndex(4);
}
}
}
You need to add wait for cityModal webelement, because on page load your dropdown is nit visible:
System.setProperty("webdriver.gecko.driver","D:\\Executabel\\geckodriver-v0.21.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 20);
driver.get("http://pro.tykitksa.com/");
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
//this is wait for se-pre-con-home element will be invisible
wait.until(ExpectedConditions.invisibilityOf(driver.findElement(By.xpath("//div[#class=\"se-pre-con-home\"]"))));
List<WebElement> dropDownList = driver.findElements(By.id("user_event_city"));
System.out.println(dropDownList.size());
for (int i = 0; i < dropDownList.size(); i++) {
System.out.println(dropDownList.get(i).getText());
WebElement Dropdown = driver.findElement(By.id("user_event_city"));
Select select = new Select(Dropdown);
select.selectByIndex(4);
I am trying to capture the prices in a list and print them. However the execution stops in the search result page and does not print the prices. I think it is because of the level of Xpath (probably I am not selecting from the upper levels?). I am confused because the Xpath I have created, when I use that in the Firepath it selects 39 matching nodes.
Thanks in advance for your time and advice.
Code:
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Flight {
public static WebDriver driver;
//This following section is for browser and getting the url
public static WebDriver browser(){
driver= new FirefoxDriver();
driver.get("https://www.orbitz.com/Flights");
return driver;
}
//this following section is getting the properties of the page
public static void getPageProperties(String ff,String ft, String fd, String rd){
WebElement flyFrom= driver.findElement(By.id("flight-origin"));
WebElement flyTo= driver.findElement(By.id("flight-destination"));
WebElement flyDate= driver.findElement(By.id("flight-departing"));
WebElement returnDate= driver.findElement(By.id("flight-returning"));
WebElement flight_search_btn= driver.findElement(By.id("search-button"));
flyFrom.sendKeys(ff);
flyTo.sendKeys(ft);
flyDate.sendKeys(fd);
returnDate.sendKeys(rd);
flight_search_btn.click();
}
// this following section will have the arguments that we will provide for flight search
public static void testFligthSearch(){
Flight f= new Flight();
f.browser();
f.getPageProperties("MSP", "SEA", "05/01/2017", "05/05/2017");
List<WebElement> pricelist= driver.findElements(By.xpath("//span[contains(#class,'dollars')]"));
for(WebElement e: pricelist){
System.out.println("The prices are: " + e.getText());
}
}
public static void main (String [] args){
Flight f= new Flight();
f.testFligthSearch();
}
}
Problem: No price is printed.
You are facing this problem because all the results have not been loaded yet so you have to wait until all search results are loaded, so you need to wait until the search results progress bar has reached 100% as following :
WebElement progressBar = driver.findElement(By.cssSelector("#acol-interstitial > div > div"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.attributeContains(progressBar, "style", "width: 100%;"));
List<WebElement> pricelist= driver.findElements(By.cssSelector("ul#flightModuleList div.offer-price.urgent > span.visuallyhidden"));
for(WebElement e: pricelist){
System.out.println("The prices are: " + e.getText());
}
package Chrome_Packg;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class testFirefox_DragDrop {
public static void main(String[] args) throws InterruptedException {
WebDriver driver=new FirefoxDriver();
driver.get("http://jqueryui.com/droppable/");
WebElement drag=driver.findElement(By.xpath("/html/body/div[1]"));//drag element
WebElement drop=driver.findElement(By.xpath("/html/body/div[2]"));//drop element
Actions action=new Actions(driver);
Thread.sleep(3000);
action.dragAndDrop(drag, drop).perform();
}
}
After executing the code, using Run as java application, in output I am getting nothing.
Here is the code snippet for the same website that you are trying on and you can also find the example here selenium Drag and Drop example
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("http://jqueryui.com/droppable/");
//Wait for the frame to be available and switch to it
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector(".demo-frame")));
WebElement Sourcelocator = driver.findElement(By.cssSelector(".ui-draggable"));
WebElement Destinationlocator = driver.findElement(By.cssSelector(".ui-droppable"));
dragAndDrop(Sourcelocator,Destinationlocator);
String actualText=driver.findElement(By.cssSelector("#droppable>p")).getText();
Assert.assertEquals(actualText, "Dropped!");
I've been trying to create a small program to put items into a cart. Its supposed to go the page where the item is located and add it to the cart. Then, all the billing information would be input by using the data in a different java class. Every time I run this code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import org.openqa.selenium.By;
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.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Supreme {
public static void main(String[] args) throws Exception{
long start = System.nanoTime();
WebDriver driver = new FirefoxDriver();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
driver.get("http://www.supremenewyork.com/shop/hats/selassie-beanie/grey");
WebElement add = driver.findElement(By.name("commit"));
add.click();
driver.get("https://www.supremenewyork.com/checkout");
AccountInfo a = new AccountInfo();
a = a.getAccount();
WebElement name = driver.findElement(By.id("order_billing_name"));
name.sendKeys(a.getName());
WebElement email = driver.findElement(By.id("order_email"));
email.sendKeys(a.getEmail());
WebElement phone = driver.findElement(By.id("order_tel"));
phone.sendKeys(a.getPhone());
WebElement address1 = driver.findElement(By.id("order_billing_address"));
address1.sendKeys(a.getAddress1());
WebElement address2 = driver.findElement(By.id("order_billing_address_2"));
address2.sendKeys(a.getAddress2());
WebElement city = driver.findElement(By.id("order_billing_city"));
city.sendKeys(a.getCity());
WebElement zip = driver.findElement(By.id("order_billing_zip"));
zip.sendKeys(a.getZip());
Select state = new Select(driver.findElement(By.id("order_billing_state")));
state.selectByVisibleText(a.getState());
Select type = new Select(driver.findElement(By.id("credit_card_type")));
type.selectByVisibleText(a.getType());
WebElement credit = driver.findElement(By.id("credit_card_number"));
credit.sendKeys(a.getCredit());
Select creditmonth = new Select(driver.findElement(By.id("credit_card_month")));
creditmonth.selectByVisibleText(a.getExpMonth());
Select credityear = new Select(driver.findElement(By.id("credit_card_year")));
credityear.selectByVisibleText(a.getExpYear());
WebElement cvv = driver.findElement(By.id("credit_card_verification_value"));
cvv.sendKeys(a.getCVV());
List<WebElement> check = driver.findElements(By.className("iCheck-helper"));
for(WebElement w : check){
w.click();
}
WebElement process = driver.findElement(By.name("commit"));
process.click();
}
}
I get this error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"order_billing_name"}
Thanks for the help!
Looks like timing issue to me. After you redirect to checkout, you might want to wait for the elements before interacting. See Explicit Waits in documentation.
WebDriverWait wait = new WebDriverWait(driver, 60);// 1 minute
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("order_billing_name")));
driver.findElement(By.id("order_billing_name")).sendKeys(a.getName());
you must check is this element in and IFRAME if yes then first switch into iframe and secondly if by ID is not working then Use Xpath or CSS path can you please share HTML source with me.