Getting Exception: Element is not clickable because another element obscures it [duplicate] - java

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

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

How to write explicit wait until a particular WebElement is located

This is a sample code for the explicit wait:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath-here")));
I want to pass WebElement as a parameter in method and wait until that WebElement is located:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(MyWebElement));
I am not sure whether such option is already there and can be done in a different way as in my case I am getting an exception as I am passing WebElement in place of By.xpath("") which is not the correct way.
You need to use the visibilityOf expected condition.
The code will be like:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOf(MyWebElement));
Hope it helps you!
Yes, you cannot pass the web element in place of XPath because the method 'visibilityOfElementLocated()' will accept only By locator.
Suppose, your method is like below :
public static void waitUntilLocated(WebDriver driver, int waitingTime, By locator) {
new WebDriverWait(driver, waitingTime).until(ExpectedConditions.visibilityOfElementLocated(locator));
}
Then You can store the By locator like below :
By someXPath = By.xpath("some xpath here");
Then you can pass 'By locator' to the method as a parameter
waitUntilLocated(driver, 30, someXPath);
Below is the whole code :
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test1 {
public static void waitUntilLocated(WebDriver driver, int waitingTime, By locator) {
new WebDriverWait(driver, waitingTime).until(ExpectedConditions.visibilityOfElementLocated(locator));
}
public static void main(String ...ali) throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName("chrome");
WebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:1234/wd/hub"), capabilities);
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("Alicse3"+Keys.ENTER);
// Checking element is located or not?
By someXPath = By.xpath("some xpath here");
waitUntilLocated(driver, 30, someXPath);
// Checking some other element
By someId = By.id("some id");
waitUntilLocated(driver, 30, someId);
}
}
Or you can do like below if you want to pass Web Element to the method and don't want to use 'visibilityOfElementLocated()' :
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test1 {
public static void waitUntilLocated(WebDriver driver, int waitingTime, WebElement element) {
new WebDriverWait(driver, waitingTime).until(ExpectedConditions.visibilityOf(element));
}
public static void main(String ...ali) throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName("chrome");
WebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:1234/wd/hub"), capabilities);
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("Alicse3"+Keys.ENTER);
// Checking element is located or not?
WebElement element = driver.findElement(By.xpath("Some XPath"));
waitUntilLocated(driver, 30, element);
// Checking some other element
element = driver.findElement(By.id("Some ID"));
waitUntilLocated(driver, 30, element);
}
}
I hope it helps...

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.

Not able to perform drag & drop using Actions

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!");

Selenium Web Driver is unable to locate element

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.

Categories

Resources