Java: String equals not working for innerHTML text - java

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 .

Related

Issue with selecting date from calendar in Selenium

I'm trying to select current date from the calendar on this website "www.makemytrip.com".
Using these 2 lines of code:
driver.findElement(By.xpath("//label[#for='departure']")).click();
To open the calendar and to select date:
driver.findElement(By.cssSelector(".DayPicker-Day.DayPicker-Day--selected.DayPicker-Day--today")).click();
The first one is working fine as it opens up the calendar but cssSelector is not responding. I've tried various variations but still it remains unresponsive.
Try this xpath strategy:
//div[#class='DayPicker-Day DayPicker-Day--today']
Now, i write in python, so you may translate my code to Java, since most of it remains same.
time.sleep (Thread.sleep in Java) here is optional Ideally you should use WebdriverWait instead of Thread.sleep. But just to show you, I used it.
driver.get('https://www.makemytrip.com/')
time.sleep(3)
driver.find_element(By.XPATH, "//label[#for='departure']").click()
time.sleep(1)
dx = driver.find_element(By.XPATH, "//div[#class='DayPicker-Day DayPicker-Day--today']")
print(dx.text)
dx.click()
Here is the output:
17 is the date and the other value is currency.
17
₹ 9,418
Process finished with exit code 0

Failed to execute 'evaluate' on 'Document', wrong xpath expression

I have calendar and I want to pick a proper day, test will be executed everyday and I have method which takes today's date.
I have WebElement pickDay which should find wanted day, the HTML code is:
<td class="class" <data-hanlder="selectDay" data-month="5" data-year="2018">
<a class="classX">5</a>
</td>
and xPath expression is (for example):
String whichMonth = "5"
String whichDay = "5"
day = driver.findElement(By.xpath("//*[contains(#text(),"+whichDay+") AND (#data-month,"+whichMonth+")]"));
But intellij keeps telling me:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[contains(#text(),5) AND (#data-month,5)]' is not a valid XPath expression.
And I dont really know what the problem is with this expression.
1) text() is a function, not an argument. # not needed here
2) don't use contains() for month to avoid mess (1, 10, 11, 12 for example)
Try the following one:
//*[#data-month="+whichMonth+"]/a[text()="+whichDay+"]
Please try following, because it looks like there is missing apostrophes in your xpath :
day = driver.findElement(By.xpath("//*[contains(text(),'"+whichDay+"') AND (#data-month,'"+whichMonth+"')]"));

how to perform action on WebElement list in Selenium

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.

Android : Retrieve multiples Elements from Html using JSoup

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

Not able to input date using sendKeys in Selenium WebDriver

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.

Categories