for-loop,selenium-webdriver , For loop not only passing once

For loop not only passing once


Tag: for-loop,selenium-webdriver
      String[] expected = new String[10];
    //{"Acapulco","Frankfurt","London","New York","Paris","Portland","San Francisco","Seattle","Sydney","Zurich"};
    expected[0] = "Acapulco";
    expected[1] = "Frankfurt";
    expected[2] = "London";
    expected[3] = "New York";
    expected[4] = "Paris";
    expected[5] = "Portland";
    expected[6] = "San Francisco";
    expected[7] = "Seattle";
    expected[8] = "Sydney";
    expected[9] = "Zurich";

    List<WebElement> allOptions = driver.findElements("fromPort"));

 // match the fromPort list value against the expected Array
    for (int i = 0  ; i < (expected.length) && i < allOptions.size(); i++) {

         String optionValue = allOptions.get(i).getAttribute("value");

         if (optionValue.equals(expected[i])) {
             System.out.println("PASSED on: " + optionValue + " we had: "+ expected[i] );

         else {
             System.out.println("FAILED on: " + optionValue + " we expected: " + expected[i]);
    //close Firefox

When executing the loop is only going round once then it exists... So it executes: PASSED on: Acapulco we had: Acapulco then exits the loop...

This is following on from my other comment: My Other Comment

New to all this Java and Selenium....

I am assuming its something to do with the Size of it only being 1; but not sure how to increase/overcome this

HTML snippet added as requested in comments:


<td align="right">
    <font face="Arial, Helvetica, sans-serif" size="2">


    <select name="fromPort">
        <option value="Acapulco"></option>
        <option value="Frankfurt"></option>
        <option value="London"></option>
        <option value="New York"></option>
        <option value="Paris"></option>
        <option value="Portland"></option>
        <option value="San Francisco"></option>
        <option value="Seattle"></option>
        <option value="Sydney"></option>
        <option value="Zurich"></option>


Please use the following code to select all options. The code you are trying to use selects the select element itself and not the options.

List<WebElement> allOptions = driver.findElement("fromPort")).findElements(By.tagName("option"));


How to get selected option using Selenium WebDriver with Python?

How to get selected option using Selenium WebDriver with Python: Someone have a solution for a getFirstSelectedOption? I'm using this to get the select element: try: FCSelect = driver.find_element_by_id('FCenter') self.TestEventLog = self.TestEventLog + "<br>Verify Form Elements: F Center Select found" except NoSuchElementException: self.TestEventLog = self.TestEventLog + "<br>Error: Select FCenter element...

iterating over a table passed as an argument to a function in lua

I am trying using the for _ in pairs() notation to iterate over a table within a function, but if I type anything, even gibberish like print('asdgfafs'), nested inside the for loop, it never gets printed. Code: record = {bid1,bid2,bid3} bid1 = {bidTime = 0.05,bidType = 'native'} bid2 = {bidTime...

Selenium can't seem to find and click a button on website? - Python

I am trying to make software that automaticly collects data for me from website. It searches for specific term, and then it should press LOAD MORE button at the end of page, and keep clicking it until it loads all the 'gigs'. Anyway, I have good idea of how...

Java - allocation in enhanced for loop

I have small problem in java with allocation of my object in "enhanced for loop". I tried something like this, which gives me later nullPointerException: SomeClass tab[] = new SomeClass[100]; for( SomeClass x : tab){ x = new SomeClass(); } So... Earlier I code in C++ and It was possible...

I want to find the xpath for day separated by

I have an HTML like this <td class="FormLabel" valign="top"> <span class="DataLabel">Consists of:</span> </td> <td class="FormData"> <span class="BodyText"> Sunday<br> Monday<br> </span> </td> Here I want Xpath to just check for Sunday. I had written Xpath like this //span[contains(.,'Consis')]/parent::td/following-sibling::td/span[contains(.,'Sun')] But this is not working as it is showing both days sunday and...

for of loop querySelectorAll

Mozilla states that "for of loops will loop over NodeList objects correctly". (source: However, this doesn't work in Chrome 43. Is this incorrect documentation or a browser bug? The copied example code used on a page with checkboxes: var list = document.querySelectorAll( 'input[type=checkbox]' ); for (var item of list)...

Cancel last line iteration on a file

I need to iterate on a file, stop iteration on a condition and then continue parse the file at the same line with another function (That may change so I can't just add content in the previous function). An example file (file.txt) : 1 2 3 4 5 6 7...

How are the results for count different in all these three cases?

Code 1: iteration = 0 count = 0 while iteration < 5: for letter in "hello, world": count += 1 print "Iteration " + str(iteration) + "; count is: " + str(count) iteration += 1 Code 2: iteration = 0 while iteration < 5: count = 0 for letter in...

Filling PHP array with “for” loop

I'm trying to populate an array in PHP as following : <?php $maxPages = 20; for ($i = 0; $i <= $maxPages; $i++) { $url = ''.$i; $targets = array( $url => array( CURLOPT_TIMEOUT => 10 ), ); } print_r($targets); ?> However it only seems to display the last populated...

How to select a text from the autocomplete textbox using selenium

I need to enter some text in a autocomplete textbox. Then I will select a option from that autocomplete option and need to click it. I have tried with the following code: public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub String textToSelect = "headlines today";...

Create a Triangular Matrix from a Vector performing sequential operations

I have been trying to solve the following problem. Suppose I have the following vector: aux1<-c(0,0,0,4,5,0,7,0,0,10,11,12) where the numbers represent the number of the row. I want to calculate the distance between the differents elements of this vector fixing the first component, then the second and so on. If the...

Combining multiple for loops into one using the OR operator

This is probably a simple question, but I can't get it to work. I've searched and have tried all the suggestions people gave for the OR operator ||, but my code just won't properly use it. So here's what I've got: This part of my code looks at a vector...

Why cant I refer to a random index in my 4D list, while I know it exists?

I got a 4D list, and I want where I want to display only the [k][3][j][z], but this isnt working. I checked all the counts and they are all 5+, so 3[4] should work... for (int k = 0; k < lijst4D.Count; k++) { for (int i = 0; i...

iteration (for-loop) ms Access with past value

I tried to translate a code from VBA excel to access. My data is a column of prices and I want to compute the returns. This is the original VBA code in excel: DerCol = Cells(T.Row, Columns.Count).End(xlToLeft).Column Cells(T.Row, DerCol + 1) = "Returns" For i = T.Row + 2 To...

Checking element existence on the page with WebDriver findElements().isEmpty method

I wish to check if some element exists on the page or not. I already saw this WebDriver: check if an element exists? issue but I'm wondering why not simply apply findElements().isEmpty method? I thought it would do the same work. UPD Now I see findElements().isEmpty works perfect so I'm...

Value attribute of a text box retains old value even after new value has been keyed in

This is the HTML I have for a text box on a form: <input type="text" onblur="javascript:itemLostFocus('18A3461989AC0244E050A20AB17C4671');" onkeydown="javascript:itemChanging('18A3461989AC0244E050A20AB17C4671');" value="972" name="18A3461989AC0244E050A20AB17C4671" maxlength="3" size="3"/> What I do next is update the text box input to 123 from 972. Now if I check the value attribute of the same text box using the getAttribute("value")...

swift iterate on array

i would like to ask a little help. I have a method which call a webservice and get a json object from it. it's look like this way: func wsServiceFeedTst() { println("WS called...") println("tstFrames count: " + tstFrames.count.description) let json = JSON(url:"") println(json) for (k, v) in json["bkkKallerFeedTst"] { let...

Python For Loop Using Math Operators

Ok, I'm in the process of learning Python, and had a quick question about for loops. I was wondering if you could use math operators in them, like JavaScript. For example, could I do: for i = 0, i < 5, i++: #code here Now, I'm quite aware that Python...

Javascript: Forloop Difference between i++ and (i+1)

I was building a javascript for loop and I want to compare the value of an array to the next value in the array. If both values are not equal, I want to return true, otherwise I want to return false. In the code below I pass the string "aba",...

Matlab: Looping through an array

This is my one dimensional array A. containing 10 numbers A = [-8.92100000000000 10.6100000000000 1.33300000000000 ... -2.57400000000000 -4.52700000000000 9.63300000000000 ... 4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000]; I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8 (a(1)+a(2))/2 - value stored in one block of...

How to iterate through a table in its exact order?

If i try to output this table, they are looped through in the false order: local letters = {DIN1="hi", AIN1= "my", AIN2 ="name", DIN2="is"} for name, value in pairs(letters) do print(name,value) end Expected Output: DIN1 hi AIN1 my AIN2 name DIN2 is Output: AIN1 my DIN2 is DIN1 hi AIN2...

Jekyll and Liquid for-loop

I want to create a little side navigation vor on-page navigation. The site contains multiple images one above the other, the navigation is inside every single image and is linking to the individual id's. I am using jekyll with the liquid templating engine. To not hard code every single element...

Change a Script to a For Do Done Loop

I have a script that I need to turn into a loop, the script works exactly as I need it to (My Awk-fu is extremely weak, so be nice) when I put in the file name like the example below. #!/bin/bash awk -v FS='(<LastName>|<\/LastName>)' '{print $2}' 17822624.xml >> test.csv awk...

CSS Selector-How to locate Parent Element

Is there any way to locate parent element in CSS Selector? i am using below code but i am not getting the parent element. WebElement we=dr.findElement(By.cssSelector("div[id='gf-BIG']:parent")); I know there is a way in Xapth but please let me know that how we can locate parent in CSS Selector. ...

VHDL average of Array through for loop

I have an Array of X Integer values in VHDL declared as a variable inside a process. I would like to calculate the average of all Values in a for loop. If I write it out for 3 Values manually everything works fine (tested on hardware): entity MyEntity is Port(...

Why is my C code printing out an extra line of rows?

#include <stdio.h> #define rows 500 //can define rows as any number int main() { int i,j; for(i=0;i<=rows;++i) { for(j=0;j<(2*i+1);++j) { printf("* "); } printf("\n"); } return 0; } So here is my code, what it does is it prints the number of rows set by #define and creates a right...

How to use list comprehensions to make a dict having list of list as values

I Have a list as following and I want to convert that as output shown below using List comprehensions. Any help is appreciated. a = [{'type': 'abc', 'values': 1}, {'type': 'abc', 'values': 2}, {'type': 'abc', 'values': 3}, {'type': 'xyz', 'values': 4}, {'type': 'xyz', 'values': 5}, {'type': 'pqr', 'values': 6}, {'type':...

For-loop does not go over all objects

Why does this for-loop not go through all items: temp = 0 for br in my_list : temp +=1 #other code here #my list is not used at all, only br is used inside here my_list.remove(br) print temp assert len(my_list) == 0 , "list should be empty" So, assertion fires....

Create a new loop without quotation marks

I wrote a function on python that should print the sentences below. def write_to_file(matrix, path): f = open(path, "w") f.write('\r\n') for i in range (2,5): item = (bestQuarterRate(matrix, i)) item = (str(item)) print item f.write(item) f.close() The problem is that I get this: ('Highest quarter rate is between', '1/1/15', 'and',...

php for loop of an array

I have an html form that passes an array into php and then does a for loop to print out values. This is the code that I have $payloads = $_POST['topay']; $loadNum = $_POST['loadnum']; $unit = $_POST['unit']; $driver = $_POST['driver']; for($i=0;$i<count($payloads);$i++) { echo $payloads[$i]; echo "<br>"; echo '<td width="50" valign="top">'.$loadNum[$i].'</td>';...

Java print result every 10th iteration of a for loop

I'm trying to write simple function to print a message every 5th or 10th iteration of for loop. for example: In this code I want to print i each tenth iteration: private void calc() { int broadcast_by_percent = 100 / 10; int calculate = 0; for (int i = 0;...

R Creating a Character Column from a Numeric Column w/o using For Loop

I am trying to create a column of characters based on an existing column of numbers, preferably without using a for loop. I have come up with a variety of ways to do this, but I keep feeling like I'm making this far more complicated than it needs to be....

for-loop add columns using SQL in MS Access

I am trying to add n columns to a table, like in this example of code where n = 10: Sub toto() Dim db As Database, i As Integer Set db = CurrentDb() For i = 1 To i = 10 db.Execute " ALTER TABLE time_series " _ & "ADD...

Printing off the content of Array or Set using for loop

When trying to print off the content of Set or Array using for loop I don't receive values but number of them. For example: var favouriteSports: Set = ["Snowboarding", "Skateboarding", "Surfing"] for genre in favouriteSports { print("\(genre)") } What I wanted to receive in console is "Snowboarding, Skateboarding, Surfing" but...

selenium webdriver - xpath locator not working if element's text contains Unicode Characters

I'm trying to select an option contained inside a menu. It's not a select menu, but it's styled to appear as such. Anyway, if the text contained inside the menu is in English, I can select it ok. Trouble is, the text I need to select is french so it...

Find element by class name

I'm trying to find one tag using we.find_element_by_css_selector('p.p1.transfer').text The problem is that there is sometimes a 'strong' tag before the tag I'm searching for which is very similar but it's class is: class="ng-binding ng-hide" instead of class="ng-binding". But when I try to find it it finds the first tag....

Add XElement dynamically using loop in MVC 4?

i will like to add the Xelement in Xdocument but how can i add in dynamically using loop? I need to capture the user multiple answer and generate the Xelement dynamically. Please guide me or provide any hint. Thanks alot! [HttpPost] public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel, int Survey_ID, string Language) {...

Tallying incorrect answers for Javascript game

So I am trying to make a javascript game for my geography class but I have run into some trouble, I can ask the questions and tell you if you're wrong or not but I would like to be able to keep track of the wrongs answers. I want to...

Java for loop only executing once

Sorry to ask such a basic question but other questions on here don't seem to fix the problem and I've been staring at it for quite a while now. I'm writing some code to find the smallest common multiple for the numbers from 1 to 20. From debugging, the outer...

How to build a 'for' loop with input$i in R Shiny

In my shiny app, I build a a number of checkboxes using a for loop, like this: landelist <- c("Danmark", "Tjekkiet", "Østrig", "Belgien", "Tyskland", "Sverige", "USA", "Norge", "Island") landecheckbox <- c() for (land in landelist){ landechek <- paste0("<label class=\"checkbox inline\"><input id=\"", land, "\" type=\"checkbox\" checked><span>", land, "</span></label>") landecheckbox <- c(landechek,...

Selecting elements by ng-model attribute with selenium-webdriver

I am using Ruby and the gem selenium-webdriver I am working with an angular form that I have no control over and would like to know how to find elements via their ng-model attributes. Here is an example select element: <select class="medium-3 small-12 columns ng-pristine ng-valid ng-touched" ng-model="ctrl.type" ng-options=" for...

Selenium C# Element Not Found Taking a Long Time

I am using Selenium for C# to test a page. Is there a way to quickly fail if the element is not found on the page? I am experiencing if the HTML element is not found on the page the Selenium test a very long time and then eventually it...

Not able to click ExtJS Dropdown button and select list elements - Selenium Webdriver Java

I am having difficulty in clicking a drop down and selecting option from the list. Below screenshot of the application. Our application uses heavy ExtJS and below is the HTML code for dropdown button and textbox. <div id="combobox-1115-bodyEl" class="x-form-item-body x-form-trigger-wrap-focus" role="presentation" style="width: 325px;"> <div id="ext-gen1273" class="x-hide-display x-form-data-hidden" role="presentation"></div> <input id="ext-gen1272"...

Using for loop indices in variable generation SAS

I would like to set up a for loop in SAS where I would like to create time dependent tables. The idea is rather simple. I have multiple tables where I would like to left join them and i would like to this operation for every month. I dont have...

Run 3 variables at once in a python for loop.

For loop with multiple variables in python 2.7. Hello, I am not certain how to go about this, I have a function that goes to a site and downloads a .csv file. It saves the .csv file in a particular format: name_uniqueID_dataType.csv. here is the code import requests name =...

What can be used if I want to check if the element is present or not in selenium webdriver?

I just want to check if the element is present on the page or not? I am confused with what can be used. What is feasible to use isDisplayed() or isPresent()? What is the difference between these two?...

looping variable in swift

i want to change this variable become looping in swift: var image1 = UIImage(named: "image1") var image2 = UIImage(named: "image2") var image3 = UIImage(named: "image3") var image4 = UIImage(named: "image4") var image5 = UIImage(named: "image5") var image6 = UIImage(named: "image6") var image7 = UIImage(named: "image7") images.append(image1!) images.append(image2!) images.append(image3!) images.append(image4!) images.append(image5!)...

Objective C for loop delay

I have a for loop that I want to add a delay between iterations. I have changed waitUntilDone to YES and get the same results. My array only has two numbers in it and both are called after the five seconds instead of: 0s - nothing 5s - Block called...

Selenium WebDriver: unable to locate element inside iframe using TinyMCE editor

Maybe my question is similar to this Selenium WebDriver NoSuchElementException: Unable to locate element however I still can't find required element. The element itself looks: body id="tinymce" class="mceContentBody" contenteditable="true" onload="window.parent.tinyMCE.get('compose_295_composeEditor').onLoad.dispatch();" dir="ltr" style="overflow: auto;"> the iframe containing this element is: body id="tinymce" class="mceContentBody" contenteditable="true"...

Matlab: For loop with window array

This is my one dimensional array A, containing 10 numbers: A = [-8.92100000000000 10.6100000000000 1.33300000000000 ... -2.57400000000000 -4.52700000000000 9.63300000000000 ... 4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000]; I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8 (a(1)+a(2))/2 - value stored in one block of...