Unable to click on 16th element from sub menu list - selenium

Because its lying beneath the page and when we scroll down, then we can see the elements, how to handle this kind of scenarios?

You can use the following method. It will scroll down untill it reaches the given element.
public static void scrollToReachAnElement(String xpath){
try {
WebElement element = d.findElement(By.xpath(xpath));
((JavascriptExecutor) d).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

You can use following function of your Selenium driver for scrolling into view
executeScript(JavaScript code here to scroll down)
JavaScript code can be
"arguments[0].scrollIntoView()", your16thWebElement
Or
"window.scrollTo(0, document.body.scrollHeight);"
or any other JavaScript code to scroll down

Related

Selenium ignore if element not present

I have the below code for my selenium, where I need to click on carousel icons and get all the images one by one, but sometimes that carousel doesn't have more than one image and thus arrow icon is not present and clickable.
new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();
How can I handle the exception where the element is not clickable ??
Two ways to fix it
Use findElements that would return a list of web element if found otherwise size of list will be 0
try {
if (driver.findElements(By.cssSelector(".arrow-icon ")).size() > 0 ) {
System.out.println("Size is > 0 so there must be at least one web element, do some interaction below like click etc");
new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();
}
else {
System.out.println("Size is 0, so web element must not be present, do something here that would make it available");
}
}
catch (Exception e) {
// TODO: handle exception
}
Use risky code inside directly try
try {
new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();
}
catch (Exception e) {
// TODO: handle exception
}

I am trying to automate Flipkart where while trying to click on submenu of the header menu it is getting detaching from the DOM, how to handle this?

The submenus are getting appeared in the DOM only when we hover over the main menu.
So after hovering over main menu using Actions class the submenus are coming, but then again when I am trying to get into the submenu it is getting detached from the DOM.
Please help me on this.
public void goToMenTopWearSectionFromFashion() throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Actions act=new Actions(driver);
try {
act.moveToElement(FashionHeaderLink).perform();
}
catch(Exception e)
{
act.moveToElement(driver.findElement(By.xpath("//div[#class='_1psGvi SLyWEo']//div[text()='Fashion']"))).perform();
}
try {
if(driver.findElement(By.xpath("//*[#class='_3XS_gI _7qr1OC']//a[1]")).isDisplayed())
{
System.out.println(driver.findElement(By.xpath("//*[#class='_3XS_gI _7qr1OC']//a[1]")).isDisplayed());
driver.findElement(By.xpath("//*[#class='_3XS_gI _7qr1OC']//a[1]")).click();
}
}catch(Exception e) {e.printStackTrace();}
}
After the hover, trying to move to click on Men's Top Wear was sometimes causing it to disappear along the way. I experienced the same by hand if I moved diagonally rather than straight down. Instead,in your 2nd try block you can do the following:
if(driver.findElement(By.linkText("Men's Top Wear")).isDisplayed())
{
String urlSave = driver.findElement(By.linkText("Men's Top Wear")).getAttribute("href");
driver.get(urlSave);
}
Probably it would work with your locator, too.

Visibility of element- selenium webdriver

My script creates a new article: fills few fields and click "Submit button" at end of page.
I have written Click() function in util class like :
public void click(String xpathKey)
{
WebElement myDynamicElement = (new WebDriverWait(driver, 60))
.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(prop.getProperty(xpathKey))));
try
{
myDynamicElement.click();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
}
Waiting for visibility of element means it will wait until element will be visible on the page or on screen? My script clicks on submit button while it's not exactly visible on the page.
I am running this script since months and it's running perfectly fine. Suddenly it started giving error element is not clickable at point(213, 415). It never appeared before. Anyone has an idea, why it could have happened?
I have done many cases, where the element is not exactly visible, generally button at end of page. selenium does not scroll itself, it finds the element and performs operation.
Try this.
public void click(String xpathKey)
{
WebElement myDynamicElement = (new WebDriverWait(driver, 60))
.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(prop.getProperty(xpathKey))));
try
{
Actions act = new Actions(driver);
act.moveToElement(myDynamicElement);
act.click();
act.build().perform();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
}
The error message you are getting indicates that there is an element covering the element you are trying to click. If you read the error message carefully, it will tell you the HTML of the blocking element and that will help you find it on the page. Without more info, it's hard to tell exactly what the situation is but there are a few common causes.
You may have just closed a dialog/popup and it's not quite completely gone before you try to click. In this case, wait for some element that's part of the dialog to be invisible generally solves this problem.
There may be some wait/loading/spinner control that appears and disappears but you are clicking before it's completely gone. The solution is the same as #1, wait for some element that's part of the spinner to be invisible.
There may be some UI element like a header, footer, sidebar that is floating that covers the element you are trying to click if it's at the very bottom/top/etc of the page. These can be a real pain because you never know when the elements are going to align and be covered. One solution is to use JS to scroll the page a little more. For example, if you script is at the top of the page and you want to click something at the bottom. Doing a click will scroll the page to show that element but that puts the element at the very bottom of the page and under a floating footer. You try to click but catch the exception. Since you know you're at the bottom of the page, you scroll the page downwards by X pixels. This brings your desired element out from behind the floating footer and now you can click it.
NOTE: If you are going to click an element right after waiting for it, you should use .elementToBeClickable(locator) instead of .visibilityOfElementLocated(). It won't solve your current problem but it's a more complete and proper wait for what you are wanting to do.

Selenium Webdriver - Clicking on Banner

I am trying to click on < and > button of the banner which keeps on rotating after few seconds in amazon.in but unable to do so.
I wrote the following code but still not successful
driver.get("amazon.in");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath("//span[contains(text(),'Previous page')]")).click();
It does not click on < button on the banner which is displayed on the top of the page.
When I write code that I'm likely to reuse, I put it into functions. Here's a function to click the next and prev arrows on the banner.
public static void clickNextBanner()
{
driver.findElement(By.cssSelector("a.a-carousel-goto-nextpage")).click();
}
public static void clickPrevBanner()
{
driver.findElement(By.cssSelector("a.a-carousel-goto-prevpage")).click();
}
Try using Explicit Wait
WebElement previous =driver.findElement(By.xpath("//span[contains(text(),'Previous page')]"));
WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(text(),'Previous page')]")));
previous.click();
Use the following code to click on next > and previous < arrows of slider.
driver.get("http://www.amazon.in/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Forward navigation
for(int i =0;i<3;i++)
{
driver.findElement(By.xpath("//a[#class='a-carousel-goto-nextpage']")).click();
Thread.sleep(1000);
}
// back navigation
for(int j=0;j<3;j++)
{
driver.findElement(By.xpath("//a[#class='a-carousel-goto-prevpage']")).click();
Thread.sleep(1000);
}

Selenium Webdriver cannot click on modal dialog when the window is not in focus

I have 2 browsers open and Selenium Webdriver can switch between these two. One window is in foreground and other is in background. And in the workflow, a modal dialog opens up in the background window and thus webdriver cannot perform any actions on it. Is there any possible solution apart from getting the background window into foreground?
I am using C#.
Loop through your window handles and check for you modal dialog to appear.
string current_window = driver.CurrentWindowHandle;
foreach (string window in driver.WindowHandles)
{
driver.SwitchTo().Window(window);
if (GetModal())
{
//do actions here
break;
}
}
driver.SwitchTo().Window(current_window); //To put you back where you started.
private bool GetModal()
{
Try
{
IWebElement modal = driver.FindElementByXPath("");
return true;
}
catch
{
return false;
}
}
Based on what you put this should work. If you can't find the modal then there is probably a different issue than just the window not being in focus. If you are worried about other errors then I would say catch only the specific error in the catch and let everything else float up ElementNotFound exception.
I am using below code
try{
//your code which will generate Modal Dialog
} catch (Exception e) {
if (e.getMessage().contains("Modal dialog present")) {//For Handling modal dialog in firefox
(new Robot()).keyPress(java.awt.event.KeyEvent.VK_ESCAPE);
(new Robot()).keyRelease(java.awt.event.KeyEvent.VK_ESCAPE);
}else if(e.getMessage().contains("unexpected alert open")){//For Handling modal dialog in chrome
driver.switchTo().alert().accept();
}
}