Not able to iterate through WebElement List
Hi
I am doing some action on https://www.makemytrip.com/ under Departure. When click on Departure, it will show calendar of two months.
I am able to get two webElements with same xpath as mentioned below, now I want to go one by one, and getText() to match with user month name.
List<WebElement> month_list= driver.findElements(By.xpath("//div[#class='DayPicker-Month']"));
ListIterator<WebElement> listIter= month_list.listIterator();
while(listIter.hasNext()) {
WebElement elem= listIter.next();
System.out.println(elem.findElement(By.xpath("//div[#class='DayPicker-Caption']/div")).getText());
}
But every time, it is reporting same text :
July 2019
July 2019
However, I am expecting it should report :
July 2019
August 2019
Please guide me how can I perform anything on each element one by one.
You should try using . instead of / in you second xpath as below :-
System.out.println(elem.findElement(By.xpath("./div[#class='DayPicker-Caption']/div")).getText());
Absolute vs relative XPaths (/ vs .)
/ introduces an absolute location path, starting at the root of the document.
. introduces a relative location path, starting at the context node.
you can make use of foreach loop. Try the below code
for(WebElement monthName: month_list)
System.out.println(monthName.getText())
P.S. I doubt your Xpath ,the xpath which you wrote is the entire month calendar(that is the month name , the dates , the prices on each dates so its the entire div that you have picked)
Kindly try
List<WebElement> month_list= driver.findElements(By.xpath("//div[#class='DayPicker-Caption']"));
You can Try using,
List<WebElement> monthname= driver.findElements(By.xpath("//div[#class='DayPicker-Caption']"));
After Storing in List of Webelements you can use different kind of for Loops for getting the text.But the best preference is forEach Loop and for Iterative Loop.
forEach Loop:
for(WebElement months: monthname)
{
System.out.println(months.getText())
}
General forLoop
int length= monthname.size();
for (int i = 0; i<length; i++)
{
String name = monthname.get(i);
System.out.println(name);
}
PS: But The Best Preference is to go with forEachLoop Rather than General For Loop.
Related
I have an issue that I try to resolve.
I have a page with 4 dropdowns.
and I want to select value in each one og them.
Since the site is angular I used operation to open a drop down and other to select value.
the problem is that after clicking the dropdown to open, all the values are under the same xpath.
( the values generated after pressing the dropdown)
Example dropdown 1 19 values:
Pressing drop down 2 32 values with the same xpath
The problem is after filling dropdown 1, and passing to dropdown 2, the xpath is the same but values not changed quickly enough, So I press drop down 2 and selenium try to find values, but see values of first dropdown.
How can I make selenium (not with thread sleep) to wait until my value exists in the dropdown.
This is my code for searching a value in webelements list (meanning the drop down)
public static void clickOptionInListByXpath(String Xpath, String clickedValue)
{
Integer flag = 1;
WebElement option2;
WebDriver driver2 = WebDriverMgr.getDriver();
List<WebElement> dropdownOptions = driver2.findElements(By.xpath(Xpath));
// for (WebElement option : dropdownOptions )
for(int i= 0;i<dropdownOptions.size() && flag == 1;i++)
{
option2 = dropdownOptions.get(i);
System.out.println("\n Option is: " + option2.getText());
if(option2.getText().equals(clickedValue))
{
option2.click();
flag = 0;
}
}
}
This it my code for waiting text to be seen in single element by xpath with 1 results, not in list (xpath for more than 1 element)
public static void getWebElementByXpathWithWaitTextToBeSeen(String xpath,String text)
{
WebDriver driver2 = WebDriverMgr.getDriver();
// driver2.manage().timeouts().implicitlyWait(IMPLICIT_WAITE, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(driver2,EXPLICIT_WAITE);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath(xpath),text));
}
How I can wait until text exists in web elements list? and it will refresh the list every time ?
p.s I use sleep it will work however I want code without hard coded sleep
regards
Let me clarify the preconditions first and please correct me if I am wrong:
You have 2 identical web-elements on page that represent 2 drop-downs.
Each of them can generate N web-elements which are all identical in scope of the whole document.
The issue is: when you get all the drop-down options, there is no way to identify from which drop-down they are.
Based on given amount of information I may offer you to start from finding both drop-down elements first, and keeping references to them till you have done all your tests with them.
In this case you will be able to find not all the options, but options that are children of specific drop-down, e.g. using
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#visibilityOfNestedElementsLocatedBy-org.openqa.selenium.WebElement-org.openqa.selenium.By-
Summarizing - find both drop-downs first, and then look for the values not only by xpath, but xpath + parent dropdown.
I'm creating a simple script to visit priceline.com and then searching "N" under Departing Flights and selecting New York City (NYC) from the dropdown list.
My code successfully types into the search bar but is still unable to find the dynamic dropdown with all the relevant results. I am not sure why.
// Clicks on "Departing from?" textbox and clears it before typing 'N'
driver.findElement(By.id("flight-departure-airport0")).click();
driver.findElement(By.id("flight-departure-airport0")).clear();
driver.findElement(By.id("flight-departure-airport0")).sendKeys("N");
// Store all dynamic search results into a list
List<WebElement> departureDropdown = driver.findElements(By.id("//*['flight-departure-airport0-dropdown']/div/div/div"));
System.out.println("List: "+departureDropdown);
Expected:
I expected departureDropdown to have a length of 9 with various airports. (Nadi, New York City, Nagasaki, etc) and expect departureDropdown[i] to return one of the city names in plain text.
Actual:
My code is stuck at the list initialization. departureDropdown is empty.
You have used By.id but you have created xPath.
Try with below xPath
List<WebElement> departureDropdown = driver.findElements(By.xPath("//div[#id='flight-departure-airport0-dropdown']//div[#role='option']"));
I am using Selenium in java for testing a search wizard where I need to click on a current date. I am trying to traverse through all the dates in the calendar and if matches the current date, I click it.
The problem here is that the dates are hidden so I have to get the innerHTML attribute, then extract the date number using substring and then comparing it with Calendar.getInstance().get(Calendar.DAY_OF_MONTH) but my condition is failing every time. Have tried str.trim() and also tried to remove all the unicode characters but nothing worked. Below is the code:
WebElement day_of_month = AutoUtils.findElementByTagName(day, "span");
if(day_of_month!=null){
String innerHtml = day_of_month.getAttribute("innerHTML");
// innerHtml is "23<span class="buzz-message">Great price</span><i></i>"
// where 23 is the date i need
String exact_date = innerHtml.substring(0,innerHtml.indexOf("<span"));
exact_date = exact_date.replaceAll("\\P{Print}", ""); // have also tried exact_date.trim();
if(exact_date.equals(Calendar.getInstance().get(Calendar.DAY_OF_MONTH))){
day_of_month.click();
} else{
System.out.Println("not found"); //gets printed every time
}
}
Can somebody help?
You have to convert the int value (day of month) to String:
if (exact_date.equals(String.valueOf(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)))) {
...
}
try using innerText instead of innerHTML . innerText only gives you what is visible to the user . innerHTML gives even html and javascripts inside it.
You should be able to get "23" only and do a easy comparison.
Also, if you can show the html , it might be easy for us to help you .
I want to retrieve a title from a div, a start hour and an end hour all of that from a big div called day and inside another div called event
I need to had these items to a list but right now i'am stuck here because it can't retrieve my 3 elements.
Document doc = Jsoup.connect("http://terry.gonguet.com/cal/?g=tp11").get();
Elements days = doc.select("div[class=day]");
Elements event = doc.select("div[class=event]");
for(Element day : days)
{
System.out.println(" : " + day.text());
for(Element ev : event)
{
Element title = ev.select("div[class=title]").first();
Element starthour = ev.select("div[class=bub right top]").first();
Element endhour = ev.select("div[class=bub right bottom]").first();
System.out.println(title.text()+starthour.text()+endhour.text());
}
}
None of there is no div in that document which have only day as class argument. They all have day class combined with another class which prevents div[class=day] from finding such div. Same problem applies to div[class=event] selector.
To solve it use CSS query syntax in which . operator is used to describe class attribute
(hint: if you want to select element which has few classes you can use element.class1.class2).
So instead of
select("div[class=day]");
select("div[class=event]");
use
select("div.day");
select("div.event");
Also instead of
ev.select("div[class=bub right top]");
ev.select("div[class=bub right bottom]");
you could try using
ev.select("div.bub.right.top");
ev.select("div.bub.right.bottom]");
This will allow you to find div which has all these classes (even if they are not in same order or there are more classes then mentioned in selector).
The date field is like a calendar and I'm not able to input the date using sendKeys of Selenium WebDriver.
But "type" in the date field was working fine before with Selenium RC.
I tried using "clear()" before "sendKeys()" but this gave the error:
Caught Exception: Element is read-only and so may not be used for actions
Command duration or timeout: 10.11 seconds
sendKeys() is working fine for other text input fields.
I tried isDisplayed() to check for the element and it comes as true. Even in the browser, when running the test, the cursor goes to the date fields but doesnt type any text into them.
Use Following Code for this...
((JavascriptExecutor)driver).executeScript ("document.getElementById('dateofbirth').removeAttribute('readonly',0);");
WebElement BirthDate= driver.findElement(By.id("dateofbirth"));
BirthDate.clear();
BirthDate.sendKeys("20-Aug-1985"); //Enter this date details with valid date format
I also faced the same issue.This is what the solution I found.This worked fine for me.
Just remove the read only attribute of the input field and then do just as other input fields.
((JavascriptExecutor) driver).executeScript("document.getElementsByName('date'[0].removeAttribute('readonly');");
WebElement dateFld = driver.findElement(By.id("date_completed"));
dateFld.clear();
dateFld.sendKeys("date Completed");
For future readers of this thread, the solution posted by #Flaburgan for issue
https://github.com/mozilla/geckodriver/issues/1070
was found to work with Firefox 63 on Win7-64
"For the record, it looks like send_keys with a correctly formatted ISO date (yyyy-mm-dd) works. So for your example, can you please try to call send_keys with (like) 2012-11-02?"
If You are using a jQuery date picker object, the field should be read-only and date have to be selected from calendar object. In that case You can use 'Select' class methods of Selenium Web Driver to choose a date.
Select date = new Select(driver.findElement(By.linkText("the date want to select")));
date.click();
I have done this and works great. Take care of the format. By this you can even get the value from the control.
var dob = element(by.id('dateOfBirth'))
dob.sendKeys('20-08-1985');
expect(element(by.id('dateOfBirth')).getAttribute('value')).toBe('2015-20-08');
Hope it helps.