kk_Chiron
kk_Chiron

Reputation: 117

How to print out all the element text appended with a counter in separated lines using Selenium and Python

Code:

elements = driver.find_elements_by_xpath('//*[@id="field-options"]')
for element in elements:
    options = element.text  
    print(options)

This gives the output:

elementONE
elementTWO
elementTHREE

How can I count every element from the list and print the number before each element so it would look like:

1   elementONE
2   elementTWO
3   elementTHREE
...

Upvotes: 0

Views: 340

Answers (3)

undetected Selenium
undetected Selenium

Reputation: 193368

To append a counter starting from 1 to each list item you can use 's enumerate() function as follows:

  • Code Block:

    for count, item in enumerate(driver.find_elements_by_xpath('//*[@id="field-options"]')):
        print(count+1, item.text)
    
  • Console Output:

    1 elementONE
    2 elementTWO
    3 elementTHREE
    

Upvotes: 1

Prathamesh
Prathamesh

Reputation: 1057

Try this,

for i, element in enumerate(elements):
    options = element.text  
    print(i+1, options)

Hope this helps you!

Upvotes: 0

0buz
0buz

Reputation: 3503

Use enumerate for that:

for i, element in enumerate(elements):
    options = element.text  
    print(i, options)

The default start index is 0 so the above will output:

0   elementONE
1   elementTWO
...

You can customise it by adding the start argument:

for i, element in enumerate(elements, start=1):
    #...

Upvotes: 0

Related Questions