Android : Retrieve multiples Elements from Html using JSoup - java

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

Related

Wait until specific text will be displayed in drop down - selenium

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.

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.

Java: String equals not working for innerHTML text

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 .

GWT Element attribute removes quotes in IE

com.google.gwt.user.client.Element removes quotes in attributes when Application works on IE. I have element with <div id="mytestid"> </div>. I want to remove this id and set a new one, but when app runs on IE (I use IE9) I can not change the id properly because it puts single or double quotes around my id.
For example:
Element el = elem;
el.removeAttribute("id");
String id = "\"mynewid"\"; //I tried all possible combinations foe escaping
el.setAttribute("id", id);
But Element id is id='"mynewid"' - it puts single quotes around double quotes.
Thank you in advance!
What is wrong with this?
Its working as expected. You have set it "mynewid" by using id = "\"mynewid\"".
Try this one if you don't want double quotes around new id.
Element el = elem;
el.removeAttribute("id");
String id = "mynewid";
el.setAttribute("id", id);
Screenshot - Firefox 26.0
Screenshot - IE9

Jsoup select command operation

I am new to Jsoup.
I am able to use select command
Elements media = doc.select("[src]");
if you see this : en.wikipedia.org/wiki/States_and_territories_of_India . In that I want to have all the Names in States of India only. But there are other tables also , when I do doc.select("area[title]"); I am getting all the table information . so I am looking if in select I can tell how it is used to only for a particular table.
I think Jsoup might not address this if that is the case,can you please tell me how to achieve this
Try something like this
Element indiaTable = doc.select("table").get(2); //India table is the third (index is 2) table on page
Elements myTds = indiaTable.select("td:eq(0)"); //The states are the first column
//or you can replace the two lines of code above with this
Elements myTds = doc.select("table.wikitable td:eq(0)");
for (Element td: myTds ) {
System.out.println(td.text());
}

Categories