Selenium Web Driver is unable to locate element - java

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.

Related

Nested for loop not incrementing in the Selenium Automation script practice

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();
}

Cant select elements on Webpage

I'm having major issue trying to select menu two elements on a dropdown.I've tried xpaths, link texts and css selector but it wont select either the password button or logout button.
Xpaths used for Password button: "//*[#id='app']/header/div[3]/nav/ul/li/a"
CSS used for Logout button: ["data-logged-in-log-out-button"]
XPath used for Logout button: "//*[#id='app']/header/div[3]/nav/ul/a"
The error im getting for the select password is:
org.openqa.selenium.WebDriverException: unknown error: Element ... is not clickable at point (989, 233).
Other element would receive the click: ...
Please try with the below XPath along with the explicit wait condition.
XPath:
//*[contains(text(),'Log out')]
Can you please try -
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class A {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("url here");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Log Out")));
driver.findElement(By.linkText("Log Out")).click();;
}
}
If it still doesn't work, please try -
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class A {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("url here");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", driver.findElement(By.linkText("Log Out")));
}
}

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/form/input[1]"}

I am getting the error message:
NoSuchElementException: no such element: Unable to locate element:
{"method":"xpath","selector":"html/body/form/input[1]"}
when I try running the code below.
And the xpath is correct I already double checked
package Package;
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.firefox.FirefoxDriver;
public class Selenium1 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","C:/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/Html/tryit.asp?filename=tryhtml_checkbox");
WebElement ele =driver.findElement(By.xpath("html/body/form/input[1]"));
boolean displayedstatus = ele.isDisplayed();
System.out.println("The display status :"+displayedstatus);
boolean enablestatus = ele.isEnabled();
System.out.println("The enable status :"+enablestatus);
boolean selectedstatus = ele.isSelected();
System.out.println("The selected status :"+selectedstatus);
ele.click();
selectedstatus = ele.isSelected();
System.out.println("The selected status :"+selectedstatus);
}
}
Whenever you try searching for the elements within the iframe you must have to switch the focus to the iframe that you are dealing with.
Try this before searching for the elements within the iframe:
driver.switchTo().frame(driver.findElement(By.name("iframeTitle")));
In this case, the iframe Title is : iframeResult
Below is the code:
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.firefox.FirefoxDriver;
public class Selenium1 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","C:/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/Html/tryit.asp?filename=tryhtml_checkbox");
//switching focus to iframe
driver.switchTo().frame(driver.findElement(By.name("iframeResult")));
WebElement ele =driver.findElement(By.xpath("html/body/form/input[1]"));
boolean displayedstatus = ele.isDisplayed();
System.out.println("The display status :"+displayedstatus);
boolean enablestatus = ele.isEnabled();
System.out.println("The enable status :"+enablestatus);
boolean selectedstatus = ele.isSelected();
System.out.println("The selected status :"+selectedstatus);
ele.click();
selectedstatus = ele.isSelected();
System.out.println("The selected status :"+selectedstatus);
}
}
If you want to handle one of two checkboxes, you need to switch to iframe first and then search for the element.
driver.get("https://www.w3schools.com/Html/tryit.asp?filename=tryhtml_checkbox");
driver.switchTo().frame("iframeResult");
WebElement ele =driver.findElement(By.xpath("//input[#value='Bike']"));
If after that you want to handle elements outside iframe, you might need to switch back with
driver.switchTo().defaultContent();

Can't click on element using webdriver

I am facing a very strange problem. I am trying to open facebook>click on forgotten account link> then opening it in a new tab> click on two textboxes.
My code is :
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
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 OpenLinkInNewTabTest {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "<path>\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.facebook.com");
String ParentWindowHandle = driver.getWindowHandle();
WebElement w = driver.findElement(By.linkText("Forgotten account?"));
new Actions(driver)
.keyDown(Keys.CONTROL)
.keyDown(Keys.SHIFT)
.click(w)
.keyUp(Keys.SHIFT)
.keyUp(Keys.CONTROL)
.perform();
new Actions(driver)
.sendKeys(Keys.CONTROL + "w")
.perform();
// ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
//
// driver.switchTo().window(tabs.get(1));
// WebElement fn = (new WebDriverWait(driver, 20))
// .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#identify_email")));
// System.out.println(driver.getTitle());
// fn.sendKeys("abcdejf:");
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
if(driver.getTitle().contains("Forgotten Password ")){
Thread.sleep(5000);
driver.findElement(By.cssSelector("#identify_email")).sendKeys("adf");
driver.findElement(By.name("email")).sendKeys("ASF");
driver.close();
driver.switchTo().window(ParentWindowHandle);
break;
}
}
driver.findElement(By.name("email")).sendKeys("ASF");
}
}
However, I am unable to send value to
driver.findElement(By.cssSelector("#identify_email")).sendKeys("adf");
The element looks like:
<input id="identify_email" class="inputtext" name="email" autofocus="1" type="text">
If I write a similar code like:
System.setProperty("webdriver.chrome.driver","path\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.facebook.com");
driver.findElement(By.linkText("Forgotten account?")).click();
driver.findElement(By.name("email")).sendKeys("ASF");
driver.findElement(By.cssSelector("#identify_email")).sendKeys("adf");
It is able to click both the elements properly.
I am not seeing any element not found exception too while running it. Please help me to debug this issue.
Thanks.
UPDATE:
Running this code sometimes show
Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state
(Session info: chrome=56.0.2924.87)
Wait for this element:
WebDriverWait wait = new WebDriverWait(driver, 10);
String email = "you#domain.com";
WebElement emailInputField = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#identify_email")));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].setAttribute('value', ' " + email + "')", emailInputField);
break;
Clicking activates this element.

Can we use Web driver to test https:// sites? I am trying to work on gmail.com and it doesn't work

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.remote.DesiredCapabilities;
public class MyFirstSelTest {
public static void main(String args[]){
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.gmail.com/");
WebElement un = driver.findElement(By.id("Email"));
WebElement pwd = driver.findElement(By.id("Passwd"));
WebElement submitBtn = driver.findElement(By.id("wp-signIn"));
un.sendKeys("ValidUsername");
pwd.sendKeys("ValidPassword");
submitBtn.click();
driver.quit();
}
}
Gmail home page is opened, but no data is entered into username and password field. Can some one please help me as to what we need to do for this?
Thanks,
Mike
Try with below locators.
driver.findElement(By.cssSelector("div.email-div>input[id='Email']")).sendKeys(Email);
driver.findElement(By.cssSelector("div.passwd-div>input[id='Passwd']")).sendKeys(Email);
driver.findElement(By.id("signIn")).click();
For reasons I do not get the problem is the submit button :
Try to replace with : WebElement submitBtn = driver.findElement(By.id("signIn")); You didn't identify the submit button correctly.

Categories

Resources