I am new to Java and would like assistance on the best way to perform the following:
I wanted to grab all of the elements that belongs to a class but I want to perform a count on how many of these elements are displayed. I have set up the code to create an int counter, the findelements and the assertion but basically my question is how in java do you create a for loop to simply check if an element within the elements list is displayed, then +1 on the count?
int testNumber = 0;
List<WebElement> testItems = _driver.findElements(By.className("test"));
//Loop each element from the list and if it's displayed then +1 for test Number
Assert.assertEquals(testNumber, 4,
"Mismatch between the number of test items displayed");
Use the method WebElement#isDisplayed (documentation) to get the status of an element.
All you need to do is to setup a counter like int counter = 0. Then create a loop over all elements like for (WebElement e : testItems) { ... }. Then, inside the loop, create some sort of if (e.isDisplayed()) { ... }. And inside this you increase the counter like counter++. All in all:
int counter = 0;
for (WebElement e : testItems) {
if (e.isDisplayed()) {
counter++;
}
}
This variant uses the enhanced for-loop. You can of course use other loop variants too.
Using streams this could be made a compact one-liner like
int count = testItems.stream()
.filter(WebElement::isDisplayed)
.count();
Note that WebElements can, depending on the website, quickly stale if they aren't processed quickly after their generation. This is indicated by them throwing a StaleElementReferenceException. It happens whenever the website rebuilds itself (completely or partially), your element was then retrieved from an old state of the website and is thus invalid.
If you experience this, you may directly collect the display status of an element before finding the other elements. This decreases the time between generation and access of a single WebElement.
Related
I want to achieve the following but with a List instead of an array (Remove some element based on comparisons between a neighboring element in the array)
Interval: {
start,
end,
priority;
}
Interval[] intervals = someIntervalsSortedByStartTime();//[(1,5), (4, 5)]
for(int i=0; i<intervals.length-1; i++){
if(intervals[i] == null) continue;
if((intervals[i].end > intervals[i+1].start) ){
if(intervals[i].priority < intervals[i+1].priority){
intervals[i] = null //i.e. have the element removed.
}else if(intervals[i].priority > intervals[i+1].priority{
itervals[i+1] = null;
}else{
throw new WTFException();
}
}
}
I know With collection things are a bit different for one we need to use Iterator, ListIterator, Apache collections Iteration, or Google Collections iterator. to remove an item from the List.
ListIterator, Apache, and Google have .previous or .peek methods that can some what allow for the "look ahead" functionality thats shown in the for loop example. However if you use them in addition to .remove() if .previous or .peek was last called before .remove() the previous item will be removed and there isnt a way to specify .remove(index) you would have to call .next().next in some cases and manage getting back to where you want the iterator to be after every iteration.
Steams wont work in this case either as we cant filter based on other elements in the List i.e. we cant get a "next" in steams.
I also wanted to avoid making a temporary copy of the data and deleting the data afterwards.
What would be the best approach of achieving the desired functionality?
You can use a List like an array, you create a loop and use the methods get(int index) and remove(int index) to access/remove Elements from the list. You just have to keep track of the indexes when you delete elements. To avoid this, you can start at the end of the list and work to the beginning:
for (int i=intervals.length-1; i>=0; i--)
I was using webdriver to grab web elements with class name topredo into ArrayList.
Seeing that the web elements is increasing when screen scrolls, i use while loop to do scroll and grab.
Java code like this:
outer: while (isContinue) {
List<WebElement> all = driver.findElements(By.className("torpedo"));
/* do screen scrolling*/
}
It runs well until the last loop.
In last secode loop, i get the all.size() result 208, but in the last loop, the all.size() result is 172 while the real total size of web elements on browser is 243,and i use eclipse debug to see the list stack content.
Screenshots like this:
all.size()
content end on index 171
So my question is why all.size() less than the real size, and why the contents on index greater than 171 are unvisiable?
Thanks a lot!
As mentioned in the comment, you keeps on resetting your list for every iteration of the loop. We can initiate the List outside the loop and keep om adding elements to the list inside the loop. The code should look something like this.
List<WebElement> all = null;
outer: while (isContinue)
{
all.addAll(driver.findElements(By.className("torpedo")));
/* do screen scrolling*/
}
You can also use a set instead of list if you get duplicate elements in the list.
Set<WebElement> all = null;
outer: while (isContinue)
{
all.addAll(driver.findElements(By.className("torpedo")));
/* do screen scrolling*/
}
Am working on some programming homework and am a bit lost. The project is to select the even/odd elements of a listarray and store in another array. It is not the even numbers in each element, but the elements themselves so if an array had values "1,2,5,7,9" and returned the even elements it would give "1, 5, 9". Also have to use recursion. Would anyone be able to give me a starting point or some advice. Though about starting with 2 elements and taking 2nd element and then building up from that, but don't know how it would add on the 2nd pass
public static ArrayList<Integer> even(ArrayList<Integer> list)
ArrayList<Integer> evenlist = ListMethods.deepClone(tList);//make copy of list
if (evenlist.size()<=1) // The list is empty or has one element
{
// return null;// Return the list as is
}
if
(evenlist.size()==2)
{
//return right element
//call method again
//add to list
}
Psuedocode
int[] evens,odds;
function categorize(List<Integer> in,int idx)
if(idx>=in.length)
return
int cur = in[idx]
if(even), add to evens
else add to odds
categorize(in,idx+1)
This sounds similar to the homework I just completed, so if it is (And you're in my class!), I'll not tell you to use any terminology we haven't covered as I know it can be daunting trying to discover something new for practicals (beyond what we have to do).
First, set your exit condition. As you've already said, you have to create a new ArrayList out of the existing one. You are going to remove items from the existing ArrayList, storing the integers that are at even (or odd) indices, until the list is empty.
So your exit condition is:
if (evenList is Empty)
return evenList;
Then, work your way through the steps. I would advise determining if the Array you start with has an even of odd number of steps, something like this:
if (evenList has Even Elements)
int holderForIntsAtEvenElements = last evenList EVEN element
Note we start at the last element, so when you are coming OUT of the recursive method, this will be the last one added to your new ArrayList, and thus it'll be in numerical order. You might find this post interesting to do this: What does this boolean return mean?
We then want to remove the last element from the list and recursively call the method again.
Finally, when we hit our exit condition and start to come out, we want to add the ints we've been storing to them, e.g.:
evenList.add(holderForIntsAtEvenElements);
return evenList;
That doesn't solve one problem, which is what to do with the very first element if the list does NOT have an even number of elements - however, I'll let you try and solve that!
That's a good mix of code and pseudo code and will hopefully help to get you on the right track.
You could use a simple for loop like this:
for (int i = 0; i < list.size(); i += 2) {
System.out.println(list.get(i));
}
If you have to use recursion, here's an outline of the steps you might take. (I won't tell you exactly what to do because you haven't tried anything and it is like homework.)
Take first element and store it
Remove (new) first element from list
Call self
What I'm trying to do is set up 14 arrays that will be of both type string and double to be able to accept input into the first index, and then the next time that the user enters in their information I don't want to add that information into an index that's already been given a value, but I do want to add that new information into the next index of that array. Do I just ++Array[index]? I'm also trying to set up this program to allow the user to be able to access 1 of 3 different IFstatements at a time to input values. If they enter input into an Array in IFstatement1, and then leave IFstatement1, go to IFstatement2 to input something, and then want to come back to IFstatement1 and input data into Arrays there, will the program know to add the newest user inputs into the next index in the array by using the ++Array[index] indicator, or do I have to do something else? How do I accomplish this?
Try looking into the ArrayList object this should work for what you are looking for and it has a nice .add() function to add to the end of the list.
List<String> l1 = new ArrayList<String>();
l1.add("String");
l1.add("Another");
for (String str : l1) {
System.out.println(str);
}
This will add the strings and provide you the iterator.
If you want another with Doubles just change for or you can have one without generics that will just hold objects <> remove them. Then your for loop would traverse the objects instead.
You can't use ++Array[index] to add an element to an array in Java. As in other statically typed languages, array's are given a size when they are created and can't contain more values then their initial size. So for instance int numbers[10]; can hold 10 integer values. If you want to set the values in that array use something like this:
int numbers[10];
for (int i = 0; i < 10; i++) {
numbers[i] = 1 + 1;
}
With regards to the user input you describe, you would need to use some form of looping, maybe a while loop?
I am working to create a crawler- a java web app, in which users can define crawl jobs, which extract and store information from specific websites.
As part of this work, there is a 'loop' construct... it has a list portion, which is evaluated initially (and typically represents a list of values)... After that is the loop body, which is executed once for each item in the list (from the list portion mentioned previously).
Note that there can be a loop construct within another loop construct, and so on.
The problem is, sometimes one list can contain millions of rows of data - and the body is to be executed for each row in this list. The body has a start index value, upper bound for the index, and is incremented by one.
What I want to do is, for a single level loop, initially calculate the list value and store it in database. After that, instead of executing the body in one go, split it up into different sections so that different sections of the list are processed in parallel.
However, how do I split up a job for an n-level loop? (Ie one loop within one loop and so on.)
Is there some recommended way of doing such processing... Any tutorial or guide you could point me to, would be very helpful for me.
I suggest packing the processing logic for 1 element of the list into a Runnable or Callable, and then pass them to an Executor for execution. This will run tasks in parallel in different worker-threads. Of course it depends on how many cores your machine has, how "parallel" this will really be.
If each element of the list can be processed completely independent of all the others, than this would be the way to go for me, instead of messing around myself with Threads and dividing the list into sublists etc.
According your description, i got that you are fetching the source code of xyz website and scrap data from that.
You can use XPath and RegularExpression to do this kind of task as its best. use JSOUP for that ,it helps you a lot.
As far as parallelization is concern you can use the .select , getElementbyId, getElementByClass of JSOUP (it's a opensource). than simply put a
for(i=0 ;i< length;i++)
{
i am fetching i;
i am fetching i+1;
int temp=i+1;
if(temp>=length)
{
break;
}
}
hope this helps: http://jsoup.org
This sounds like a great candidate for the Java 7 fork / join framework
Lets say you create 3 thread: T1, T2, T3. and following is the looping construct, for eaxmple
for(int i=0; i<100; i++)
{
for(int j=0; j<100; j++)
{
for(int k=0; k<100; k++)
{
// do some processing.
}
}
}
Modify the increment part as i += no. of threads. In this case it will be i += 3
Thus, the initial values of i, j, k will vary for each thread.
For T1: i = 0;
For T2: i = 1;
For T3: i = 2;
Similary the loop limit can be set.