Search code examples
pythonlistseleniumenumerate

With python How to get only the indices of list items and use them as a variable in f-string


I'm trying to get selenium to click specific buttons on a website. To do that I need the indices of list items to be a variable in a f-string. Is there a neat way to access the indices of that list and declare them a variable? I know you can get both values, index and itemvalue of a list by enumerate, but maybe theres another way than converting the index strings into integers and work on with these. Thats what I got so far:

T3 = browser.find_elements_by_xpath("//*[@id='tabelle_merkliste']/tbody/tr[position()<25]/td[10]/img/following::td[2]")

verf3string = []

for i in T3:                     # retrieve textelement
    print(i.text)
    textelement = i.text.split('/')  
    plätze = textelement[0]      # only retrieve first position   of string
    print(plätze)

    verf3string.append(plätze)   #safe text in list


print(verf3string)

for i in range(len(verf3string)): # converting string list into list of integers to be able to compare numbers by </>
    verf3 = (verf3string[i])
    print(verf3)




for i in (verf3):
    if i > 0:
       x = verf3.index(i)
       browser.find_element_by_xpath(f'//*[@id="tabelle_merkliste"]/tbody/tr{x}/td{y}/img').click()

#this gives me the error TypeError: '>' not supported between instances of 'str' and 'int'

By Any help is appreciated, thanks!

By enumerate I meant using it to retrieve indeces. It gives me the index plus value.

for index, value in enumerate(test_list):
print(index, value)

(


Solution

  • You can just retrieve the index of the item in a list (called 'array' here) like this:

    x = array.index(i)
    

    Or just do it in the f-string:

    f'//*[@id="tabelle_merkliste"]/tbody/tr{array.index(i)}/td{y}  /img'