Search code examples
pythonseleniumselenium-webdriverenumerationenumerate

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

Solution

  • 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):
        #...