2

When you use find_by_elements it returns a list of all the elements which correspond to a selector, xpath, class, id, etc...

However, I wanted to know if it's possible to extract an element of this list in Python to click on it or at least to try to click on each element of this list.

To explain my issue: I have an xpath which points to two elements, these two elements are exactly the same thing but one is not visible and the other one is visible.

But if I use the regular find_by_element, it points to the invisible one, so I have an error...

I would like to use this list, to reach the other one and finally be able to click on this element.

4 Answers 4

1

You can find all the elements matching your locator and then filter out the visible one:

elements = driver.find_elements_by_css_selector("selector")
visible_elements = [element for element in elements if element.is_displayed()]

visible_elements[0].click()

Or, using next():

elements = driver.find_elements_by_css_selector("selector")
visible_element = next(element for element in elements if element.is_displayed())

visible_element.click()
2

You just need to access the correct index of the returned array:

list = admin.find_elements_by_xpath("your xpath")
list[1].click() #if you want to click on the second one

If you need to get the length of the array, call the function len:

len(list)
1

You could loop through the array of elements and use

if element.is_displayed(): #click element else: #do nothing

0

To put the above answer in more easier way here is the solution below. If you are locating 4 elements with same xpath: To access the first element xpath[0] To access second element xpath[1], xpath[2] for 3rd and xpath[3] for 4th.

1
  • 1
    Python arrays are 0-indexed . . .
    – ernie
    Commented Feb 17, 2017 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.