I am learning automation with selenium Webdriver(Java) and I wanted to practice some stuff on this webpage.
I am having trouble selecting a particular date using date picker. Here is my code which attempts to do that:
String parentWindow = driver.getWindowHandle();
String subWindow = null;
driver.findElement(By.xpath(".//*[#id='ns_7_CO19VHUC6VU280AQ4LUKRK0IR7_fmOutboundDateDisplay']")).click(); //Clicking on datepicker icon
// Change to a new window
String parentWindow = driver.getWindowHandle();
String subWindow = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator1 = handles.iterator();
while (iterator.hasNext()){
subWindow = iterator.next();
}
driver.switchTo().window(subWindow);
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[#class='calendarBodyContainer']/tr[2]/td[3]/span")).click(); //Departure Date- 10Feb/2015
driver.findElement(By.xpath(".//*[#class='calendarBodyContainer']/tr[4]/td[4]/span")).click(); //Arrival Dtae- 25 Feb/2015
driver.switchTo().window(parentWindow);
However, I am getting the following error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//*[#class='calendarBodyContainer']/tr[2]/td[3]/span"}
Command duration or timeout: 3.12 seconds
Please help.
The problem is you mistook the calendar widget as new window and automated accordingly, which resulted in the element not found, rightly suspected by #alecxe
Please try the below code and see if it works out for you.
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Navigating to the site
driver.get("http://www.lufthansa.com/online/portal/lh/us/homepage");
//Clicking on the Departing field to select date
driver.findElement(By.id("ns_7_CO19VHUC6VU280AQ4LUKRK0IR7_fmOutboundDateDisplay")).click();
//Selecting Feb 10, 2015 for departure date
driver.findElement(By.xpath("//td[#dojoattachpoint = 'calRightNode']//span[.='10']")).click();
//Waiting for the return calendar with "Return" as the header to appear
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#dojoattachpoint='calHeadlineNode' and contains(text(),'Return')]")));
//Selecting Feb 26, 2015 for returning date
driver.findElement(By.xpath("//td[#dojoattachpoint = 'calLeftNode']//span[.='26']")).click();
NOTE: I have added explicit wait for waiting for the Return text in the "Return Calendar widget" because it overlaps the Departing/Outbound Calendar, and hence selenium needs a little time to detect the change in DOM.
I would try two things:
try the following xpath (relying on the table element and span's text):
//table[#class='calendarContainer'][1]//span[. = '09']
explicitly waiting for an element:
WebDriverWait wait = new WebDriverWait(webDriver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[#class='calendarContainer'][1]//span[. = '09']"))).click();
I'm also not sure about the necessity of switching windows here.
Related
I have a grid where the column contents can be sorted in ascending/descending order by clicking on the row header - sk_Total_Qty_Element
To explain what the below code does it is just traversing the contents of one particular column - jqTable_SK_Product/SK row by row and printing the value in them.
Below code is giving me NoSuchElementException
#FindBy(xpath = "//thead/tr/th[#id='jqTable_SK_Total Qty']")
WebElement sk_Total_Qty_Element;
public void warehousingGridTotalQtyClick() throws Exception {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
ldriver = new ChromeDriver(options);
WebDriverWait wait1 = new WebDriverWait(ldriver, 100);
WebElement housingTotalQtyElement = wait1
.until(ExpectedConditions.elementToBeClickable(sk_Total_Qty_Element));
housingTotalQtyElement.click();
Thread.sleep(2000);
wait1 = new WebDriverWait(ldriver, 100);
housingTotalQtyElement = wait1.until(ExpectedConditions.elementToBeClickable(sk_Total_Qty_Element));
housingTotalQtyElement.click();
WebElement grid = ldriver.findElement(By.xpath("//div[#id='gview_jqTable_SK']"));
System.out.println(grid.getTagName());
Thread.sleep(2000);
List<WebElement> skList = grid.findElements(By.xpath("//td[#aria-describedby='jqTable_SK_Product/SK']"));
for (WebElement sk : skList) {
System.out.println(sk.getText());
}
}
but when I do sort the grid view in descending order I'm getting below error:
FAILED: housingGrid_TC003
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#id='gview_jqTable_SK']"}
(Session info: headless chrome=100.0.4896.88)
But when I don't do the grid sorting in descending order i.e., when I remove the below piece of code from above which basically double clicks the row header - sk_Total_Qty_Element the code runs perfectly well.
WebElement housingTotalQtyElement = wait1
.until(ExpectedConditions.elementToBeClickable(sk_Total_Qty_Element));
housingTotalQtyElement.click();
Thread.sleep(200);
wait1 = new WebDriverWait(ldriver, 100);
housingTotalQtyElement = wait1.until(ExpectedConditions.elementToBeClickable(sk_Total_Qty_Element));
housingTotalQtyElement.click();
To overcome this error I have tried to focus on the by using window handles but that did not work out and also I tried using WebDriverWait with below code and that did not work either leading to similar error
WebElement grid = wait1.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='gview_jqTable_SK']")));
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#id='gview_jqTable_SK']"}
Kindly help
You do not need to create WebDriverWait object every time like you've done it above:
new WebDriverWait(ldriver, 100);
Just create once and use the reference at multiple places.
Since you are clicking twice housingTotalQtyElement on this column with just .2 sec gap, I'd say increase this time to at least 2 seconds
so
Thread.sleep(200);
should be:
Thread.sleep(2000);
Also, instead of having just findElement like below
WebElement grid = ldriver.findElement(By.xpath("//div[#id='gview_jqTable_SK']"));
use WebDriverWait
wait1.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='gview_jqTable_SK']"))).click();
I am trying to place time gap between each web element.
For example i want first webelement should work after 10 seconds and second web element should work after 30 seconds.But thats not working for me.
And is that possible if element1 i clicked manually then 2nd will work automatically, because in current case if i click 1st one manually then 2nd element not working automatically.
driver = new FirefoxDriver(options);
driver.get("http://demo.com");
((JavascriptExecutor) driver).executeScript("window.focus();");
WebDriverWait wait = new WebDriverWait(driver, 600);
// First path
WebElement element1 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[2]/div[2]/div[2]/div/div/form/div[5]/div/input")));
element1.click();
// Second path
WebElement element2 = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='sbt67Pin']")));
element2.click();
// Third path
Try Thread.sleep() like that.If want to halt your scripts running.
Thread.sleep(10000);
WebElement element1 = driver.findElement(By.xpath("/html/body/div[2]/div[2]/div[2]/div/div/form/div[5]/div/input"));
element1.click();
hread.sleep(20000);
// Second path
WebElement element2 = driver.findElement(By.xpath("//*[#id='sbt67Pin']"));
element2.click();
// Third path
Thread.sleep(30000);
I am trying to click on dropdown value to select city in from field in Make my trip http://www.makemytrip.com/. But getting Stale element reference exception. Ids are getting changed on page load.
Tried below code:
driver.findElement(By.xpath(".//*[#id='hp-widget__sfrom']")).clear();
driver.findElement(By.xpath(".//*[#id='ui-id-1']"));
driver.findElement(By.xpath(".//*[#id='hp-widget__sfrom']")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeSelected(driver.findElement(By.xpath(".//*[#class='ui-menu-item'][2]"))));
To click on a dropdown value e.g. Mumbai you can use the following solution:
Code Block:
driver.get("https://www.makemytrip.com/")
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#class='input_fromto checkSpecialCharacters ui-autocomplete-input' and #id='hp-widget__sfrom']"))).click();
List<WebElement> myList = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//li[#class='ui-menu-item'][starts-with(#id,'ui-id-')]//span[#class='autoCompleteItem__label']")));
for (WebElement element:myList)
if(element.getText().contains("Mumbai"));
element.click();
Browser Snapshot:
You can use this working code:
WebDriver driver = new ChromeDriver();
driver.get("https://www.makemytrip.com/");
driver.findElement(By.xpath(".//*[#id='hp-widget__sfrom']")).clear();
driver.findElement(By.xpath(".//*[#id='hp-widget__sfrom']")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#class='ui-menu-item'][2]/div/p[1]/span[1]"))).click();
I have fixed the xPath of dropdown list element. Always try to specify the exact element yo want to interact with. For example if you want to click on button, try to find <span> or <button> tag, for a link <a> tag and for input fields <input> tag.
You can try this code :
I do not see any use of xpath in this scenario. I have converted some of the xpath to either css selector or id. and have kept only one. Though I have not faced any stale element reference.
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("https://www.makemytrip.com/");
WebElement from = wait.until(ExpectedConditions.elementToBeClickable(By.id("hp-widget__sfrom")));
from.click();
from.clear();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("ul[class*='ui-widget-content hp-widget__sfrom']")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//li[contains(#aria-label,'Top Cities : Mumbai, India ')]"))).click();
The below code works fine for me and it is parameterized as well, it works for any input value without changing the xpath. In this example, I took mumbai as test data.
driver.get("https://www.makemytrip.com/");
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[contains(#id,'hp-widget__sfrom')]")).clear();
driver.findElement(By.xpath("//input[contains(#id,'hp-widget__sfrom')]")).click();
driver.findElement(By.xpath("//input[contains(#id,'hp-widget__sfrom')]")).sendKeys("Mumbai");
Thread.sleep(2000);
WebDriverWait wait = new WebDriverWait(driver, 30);
By option = By.xpath("//div[#class='autoCompleteItem']/p/span[contains(text(),'Mumbai')]");
wait.until(ExpectedConditions.elementToBeClickable(option));
driver.findElement(option).click();
Not able to Select the month for Date of Birth.
Code I am using is:
driver.findElement(By.xpath(".//*[#id = 'BirthMonth']/div")).click();
Thread.sleep(3000);
WebElement months = driver.findElement(By.xpath(".//[#id='BirthMonth']/div[2]/div[#id=':1']"));
Thread.sleep(2000);
months.click();
I also tried with by using DropDownList case. But Not able to set any Month.
Please Say me the Solution.
You can use keyboard event replace mouse.
WebElement birthMonth = driver.findElement(By.id("BirthMonth"));
birthMonth.click();
Actions action = new Actions(driver);
action.sendKeys(Keys.DOWN).sendKeys(Keys.ENTER).perform();
We can use sendKeys directly:
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]")).sendKeys("July");
You can wrap this up in a function
public void selectBirthMonth(int monthIndex)
{
driver.findElement(By.cssSelector("#BirthMonth > div")).click();
driver.findElements(By.cssSelector("#BirthMonth > div.goog-menu > div.goog-menuitem")).get(monthIndex - 1).click();
}
and then call it like
selectBirthMonth(9); // 1 = January
WebElement month = wd.findElement(By.xpath("//[#id=\"BirthMonth\"]/div[1]"));
month.click();
Thread.sleep(3000);
//wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//fetch months from the dropdown and store it in a list
List<WebElement> month_dropdown = wd.findElements(By.xpath("//[#id=\"BirthMonth\"]/div[2]/div/div"));
//iterate the list and get the expected month
for (WebElement month_ele:month_dropdown){
String expected_month = month_ele.getAttribute("innerHTML");
// Break the loop if match found
if(expected_month.equalsIgnoreCase("August")){
month_ele.click();
break;
}
}
It is not drop down value , you have to click on drop down arrows and then click on any value which you have to pass from script.
Code is below:
System.setProperty("webdriver.chrome.driver", "E:/software and tools/chromedriver_win32/chromedriver.exe");
WebDriver driver= new ChromeDriver();
//FirefoxDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://accounts.google.com/SignUp");
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]/div[2]")).click();
driver.findElement(By.xpath(".//*[#id=':7']/div")).click();
it is workable code for Birthmonth
Please find below link for same type of Question
Not able to select the value from drop down list by using Select method in Selenium
I'm testing a web app, in which after opening a page I need to select a radio button after that a pop-up will appear. In that pop-up I'm selecting an ID. Once selected, it will come to main window, in which I'm trying to select a text field with ID. But I receive the following error:
Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 50.14 seconds
driver.findElement(By.xpath("html/body/section/div/div[2]/div[3]/div/div/div/div/ul/li[1]/a")).click();
driver.findElement(By.xpath("html/body/section/div/div[12]/div[1]/div/div[2]/div[3]/div/div/div/div/button[1]")).click();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
String mainWindowHandle=driver.getWindowHandle();
driver.findElement(By.xpath("html/body/div[3]/div/div")).click();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
Set s = driver.getWindowHandles();
Iterator ite = s.iterator();
while(ite.hasNext())
{
String popupHandle=ite.next().toString();
if(!popupHandle.contains(mainWindowHandle))
{
driver.switchTo().window(popupHandle);
}
}
driver.findElement(By.xpath("html/body/div[3]/div/div/div[3]/div/div/div[1]/div[2]/div[4]/div[2]/a")).click();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.switchTo().window( mainWindowHandle );
driver.findElement(By.id("Title")).sendKeys("auto title");
Problem is I cannot find the textfield with ID: Title" for inserting "auto title.
Thanks in Advance.
Instead of using sleep() with hardcoded time intervals, use an explicit wait:
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement title = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Title")));
title.sendKeys("auto title");
Finally found a solution by adding
Thread.sleep(5000);
before finding the element and it solved.