Strange behaviour of a for loop in python with selenium

8 views
Skip to first unread message

Valentin

unread,
Jun 4, 2023, 12:29:22 AM6/4/23
to Selenium Users
I have quite a strange problem. I am in the process of writing a webbot in python with selenium and would like to go through a list of elements and see if they contain an M and click on it. For this I have written the following for loop:
elements = driver.find_elements(By.CLASS_NAME, "small-margin-top")
for element in elements:
        print(element.text) 
         if 'M' in element.text: 
                   print("yes"
                  element.click()
                  break
         else
                     print("no")
If you look at the loop, you would think that the text is first printed for each element and then whether it contains an M or not, and if, break. However, all element.text is printed first and a single Yes at the end and clicks on the last element. The spacing is correkt. I think the problem is the list elements, cause it contains only 1 object, but in the documentation on the selenium website its done the same way. How can i fix it?
Reply all
Reply to author
Forward
0 new messages