Selenium Python For Loop Printing Only First Element Repeatedly

Find the data you need here

We provide programming data of 20 most popular languages, hope to help you!

Previous PostNext Post

Selenium python for loop printing only first element repeatedly

Here I am selecting the main container for each item then using for loop for getting business title from each container. Here is my code: container = Stack Overflow. About; Products For Teams; Stack Overflow Public questions & answers; Stack Overflow

container = driver.find_elements_by_css_selector(".businessCapsule--mainRow")
for i in container:
    business_title = driver.find_element_by_css_selector('.text-h2')
    print(business_title) 
Mirror & Glass Processing Ltd
Mirror & Glass Processing Ltd
Mirror & Glass Processing Ltd
Mirror & Glass Processing Ltd
business_title = driver.find_elements_by_css_selector(".text-h2")
for i in business_title:
        business_title = i.text
        print(business_title)
Mirror & Glass Processing Ltd
J.E.D Double Glazing Repairs
B & R Glazing Co.Ltd
Durham Window & Door Centre Ltd
Ken Rose Joinery & Glazing
business_title = i.find_element_by_css_selector('.text-h2')

Selenium python for loop printing only first element repeatedly

No Comments on selenium python for loop printing only first element repeatedly I am trying to get business info from this page . Here I am selecting the main container for each item then using for loop for getting business title from each container.

container = driver.find_elements_by_css_selector(".businessCapsule--mainRow")
for i in container:
    business_title = driver.find_element_by_css_selector('.text-h2')
    print(business_title) 
Mirror & Glass Processing Ltd
Mirror & Glass Processing Ltd
Mirror & Glass Processing Ltd
Mirror & Glass Processing Ltd
business_title = driver.find_elements_by_css_selector(".text-h2")
for i in business_title:
        business_title = i.text
        print(business_title)
Mirror & Glass Processing Ltd
J.E.D Double Glazing Repairs
B & R Glazing Co.Ltd
Durham Window & Door Centre Ltd
Ken Rose Joinery & Glazing

Selenium Easy

Just like decision making statements, looping statements also execute the statements based on some condition but if we want to execute the same statement more than once with condition checking then we go for looping statements. The following are the types of looping statements in Java: - 1. while loop 2. do..while loop 3. for loop 1. while loop: while loop is the basic of all

while(boolean_expression){
statements;
}
package com.seleniumeasy.controlstatements;

public class WhileDemo {
	public static void main(String[] args) {
		int i=1;
		while(i<=10){
			 System.out.println(i);
			i++;// incrementing i value.
			
		}
	}
}
while(2)// this gives error
System.out.println("while loop");
while (KeyValues.hasMoreElements()) {
String key = (String) KeyValues.nextElement();
String value = prop.getProperty(key);
System.out.println(key + ":- " + value);
}
do{
statements;
}while(boolean_expression);
package com.seleniumeasy.controlstatements;

public class DoWhileDemo {

	public static void main(String[] args) {
		int i=1;
		do{
			System.out.println(i);
			i++;
		}while(i<=10);
	}
}
for(initialization;boolean_expression;increment_decrement){
statements;
} 
package com.seleniumeasy.controlstatements;

public class ForLoopDemo {
	public static void main(String[] args) {
		for(int i=0;i<10;i++){
			System.out.println(i);
		}
	}
}
for(int i=1,j=1; i<10; j++)
for(declaration:expression){
statements;
}
package com.seleniumeasy.controlstatements;

public class ForEachDemo {
	public static void main(String[] args) {
		int a[]={1,2,3,4,5,6,7,8,9,10};  
		   for(int i:a){  
		     System.out.println(i);  
		   }  
	}
}
boolean flag = false;
		List<WebElement> listBoxItems = driver.findElements(By.tagName("li"));			            
		for(WebElement item : listBoxItems)
		{
			if(item.getText().equals(value))      		
				flag=true;
			break;
		}

For Loop In Python - Complete Guide

A for loop most commonly used loop in Python. It is used to iterate over a sequence (list, tuple, string, etc.) Note: The for loop in Python does not work like C, C++, or Java. It is a bit different. Python for loop is not a loop that executes a block of code for a specified number of times. It is a loop that executes a block of code for each

for iterator_variable in sequence:
  # loop body
  # ...
# Using for loop on list
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']

# Using for loop
# loop will run the code for each item in the list
for fruit in fruits:
    print(fruit)
orange
apple
pear
banana
kiwi
# looping over tuples
items = ('one', 'two', 'three')
for item in items:
    print(item)
one
two
three
# looping over string
items = 'looping'
for item in items:
    print(item)
l
o
o
p
i
n
g
# looping first 5 numbers
for i in range(5):
    print(i)
0
1
2
3
4
# looping between a range of numbers

# looping from 5 to 10
for i in range(5, 10): # 10 not included
    print(i, end=' ')
print()

# looping 20 to 30 (30 included)
for i in range(20, 31):
    print(i, end=' ')
5 6 7 8 9
20 21 22 23 24 25 26 27 28 29 30
# looping with step

# jumping by 2
for i in range(0, 10, 2):
    print(i, end=' ')
print()

# jumping by 3
for i in range(0, 10, 3):
    print(i, end=' ')
print()

# negative step
for i in range(10, 0, -2):
    print(i, end=' ')
print()
0 2 4 6 8
0 3 6 9
10 7 4 1
# looping with index
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']
for i in range(len(fruits)):
    print(i, fruits[i])
0 orange
1 apple
2 pear
3 banana
4 kiwi
# looping with index

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']
for i, fruit in enumerate(fruits):
    print(i, fruit)
0 orange
1 apple
2 pear
3 banana
4 kiwi
# breaking a loop

# break loop when i == 5
for i in range(10):
    if i == 5:
        break
    print(i, end=' ')
print()

# break loop when sum is greater than 100
sum = 0
for i in range(10):
    sum += i * 1
    if sum > 100:
        break
print("Sum = ", sum)
0 1 2 3 4
Sum =  45
# continuing a loop

# continue loop when i == 5 or i == 7
for i in range(10):
    if i == 5 or i == 7:
        continue
    print(i, end=' ')
print()
0 1 2 3 4 6 8 9
# adding evens
  
numbers = [5, 12, 8, 9, 10, 11, 13, 14, 15]
sum = 0
for i in numbers:
    if i % 2 != 0:
        continue
    sum += i
print("Sum = ", sum)
Sum =  44
# nested for loop
size = 5

for i in range(1, size+1):
    # nested loop
    for j in range(1, i+1):
        print("*", end="")
    print()
*
**
***
****
*****
# for loop with else
for i in range(3):
    print(i)
else:
    print("Loop Finished")
0
1
2
Loop Finished
# for loop with else and break

# else not executed with break statement
for i in range(3):
    if i == 2:
        break
    print(i)
else:
    print("Loop Finished")
print()

# else executed with break statement
for i in range(3):
    if i == 5:
        break
    print(i)
else:
    print("Loop Finished")
0
1

0
1
2
Loop Finished
for iterator_variable in sequence:
  # loop body
  # ...

Selenium , how to print elements of this html in order as they are?

You can iterate over the child of span element and print the text in case of string and alt text in case of img tag. 13. 1. from bs4 import BeautifulSoup as bs4. 2. …

   <span dir="ltr" class="i0jNr selectable-text copyable-text">
    <span>
        <img crossorigin="anonymous"
            src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="😅"
            draggable="false" class="b75 emoji wa i0jNr selectable-text copyable-text" data-plain-text="😅"
            style="background-position: -60px -40px;">
        " how "
        <img crossorigin="anonymous"
            src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="👹"
            draggable="false" class="b60 emoji wa i0jNr selectable-text copyable-text" data-plain-text="👹"
            style="background-position: -60px -40px;">
        " are you"
        <img crossorigin="anonymous"
            src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="🎂"
            draggable="false" class="b25 emoji wa i0jNr selectable-text copyable-text" data-plain-text="🎂"
            style="background-position: -40px -40px;">
    </span>
</span>
😅
 how
👹
 are you
🎂
😅 how 👹 are you 🎂
chats = driver.find_elements_by_class_name("message-in")
for i in range(0,len(chats)):
    messages = chats[i].find_elements_by_class_name("i0jNr")
    for j in range(0,len(messages)):
        if messages[j].text == "" :        
            emojis = chats[i].find_elements_by_class_name("emoji")
            for emoji in emojis:
                print(emoji.get_attribute('alt'))
                break
        else:
            print(messages[j].text)
 how
 are you
😅
👹
🎂 
from bs4 import BeautifulSoup as bs4
from bs4 import NavigableString, Tag

soup = bs4(html, 'html.parser')

s = soup.find('span', attrs={'class':'i0jNr'})
s = s.find('span')
for i in s.children:
    if isinstance(i, NavigableString):
        print(i.strip())
    elif isinstance(i, Tag):
        print(i.attrs['alt'])
😅
how
👹
are you
🎂

Selenium Easy

Webdriver offers more than one way to locate the elements of your web application in order to find the elements. You can find elements by using ID, name, XPath, CSS Selectors, and more. Know more on Locators for Selenium. Please save the below script (eg:- python_selenium_example.py), and then it can be run like below: python python_selenium

python python_selenium_example.py
from selenium import webdriver

driver = webdriver.Chrome(r'C:\Users\drivers\chromedriver.exe')
driver.maximize_window()
driver.get("http://www.seleniumeasy.com/test/basic-first-form-demo.html")
assert "Selenium Easy Demo - Simple Form to Automate using Selenium" in driver.title

eleUserMessage = driver.find_element_by_id("user-message")
eleUserMessage.clear()
eleUserMessage.send_keys("Test Python")

eleShowMsgBtn=driver.find_element_by_css_selector('#get-input > .btn')
eleShowMsgBtn.click()

eleYourMsg=driver.find_element_by_id("display")
assert "Test Python" in eleYourMsg.text
driver.close()
driver = webdriver.Chrome(r'C:\Users\pc\Downloads\chromedriver.exe')
driver.maximize_window()
driver.get("http://www.seleniumeasy.com/test/basic-first-form-demo.html")
eleUserMessage = driver.find_element_by_id("user-message")
eleUserMessage.clear()
eleUserMessage.send_keys("Test Python")
eleShowMsgBtn=driver.find_element_by_css_selector('#get-input > .btn')
eleShowMsgBtn.click()
eleYourMsg=driver.find_element_by_id("display")
assert "Test Python" in eleYourMsg.text
driver.close()

Python For Loop

The statements inside the for loop are executed for each of these elements. For these examples, the body of for loop has only one print statement. But, you may write as many statements as required by following indentation. Example 2: For Loop with List. In this example, we will take a list and iterate over the items of list using for loop

for item in iterable:
    statement(s)
for i in range(25,29):
	print(i)
25
26
27
28
mylist = ['python', 'programming', 'examples', 'programs']

for x in mylist:
	print(x)
python
programming
examples
programs
mytuple = ('python', 'programming', 'examples', 'programs')

for x in mytuple:
	print(x)
python
programming
examples
programs
mydictionary = {'name':'python', 'category':'programming', 'topic':'examples'}

for x in mydictionary:
	print(x, ':', mydictionary[x])
name : python
category : programming
topic : examples
myset = {'python', 'programming', 'examples'}

for x in myset:
	print(x)
python
examples
programming
mystring = 'pythonexamples'

for x in mystring:
	print(x)
p
y
t
h
o
n
e
x
a
m
p
l
e
s
for x in range(2, 10):
    if(x==7):
        break
    print(x)
2
3
4
5
6
for x in range(2, 10):
    if(x==7):
        continue
    print(x)
2
3
4
5
6
8
9
for x in range(2, 6):
    print(x)
else:
    print('Out of for loop')
2
3
4
5
Out of for loop
for x in range(5):
    for y in range(6):
        print(x, end=' ')
    print()
0 0 0 0 0 0
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4

Python For Loops

Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable like string, tuple, list, etc. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).

for var in iterable:
    # statements
List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz 123
abc 345
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Current Letter : e
Last Letter : s 
0 1 2 3 4 5 6 7 8 9 
10 20 30 40 
Sum of first 10 numbers : 45
1
2
3
No Break

1

Previous PostNext Post

Related code examples