2

I am using python 3.x Selenium WebDriver and I am making a for loop to go all through the elements of the page with limit the length of the elements in the class and then print number of iteration but it gets all visible and hidden elements how to get only visible element in the page.

To get all elements from the class I am using

showMore = driver.find_elements_by_class_name('getPhotos')
JeffC
  • 22,180
  • 5
  • 32
  • 55
  • is_displayed method work with only (find element) and not the list (find elements) – Noran Magdi Apr 30 '18 at 11:51
  • 1
    you could iterate through the list then insert each element into the new list if is_displayed = true? that's my last guess on this because I haven't found anything better – L_Church Apr 30 '18 at 11:59
  • @L_Church And I think this is the right approach. If the element is visible, push founded element in new collection. Then, just use the collection with founded elements. – Zhivko.Kostadinov Apr 30 '18 at 13:32

2 Answers2

1

You can take the list of all elements (visible and invisible) and filter it down to only those that are visible. There are several ways to do this... here is one.

showMore = driver.find_elements_by_class_name('getPhotos')
onlyVisible = filter(lambda x: x.is_displayed(), showMore)
JeffC
  • 22,180
  • 5
  • 32
  • 55
0

A better way to cater to your requirement will be to create a List inducing WebDriverWait with expected_conditions as visibility_of_all_elements_located as follows :

showMore = WebDriverWait(driver, 20).until(expected_conditions.visibility_of_all_elements_located((By.CLASS_NAME, "getPhotos")))

Note : visibility_of_all_elements_located refers to an expectation for checking that all elements are present on the HTML DOM of a page and are visible. Visibility means that the elements are not only displayed but also has a height and width that is greater than 0.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • glad to see this got attention ^^ – L_Church Apr 30 '18 at 13:41
  • 1
    This will not work because according to OP there are some elements that are visible and some that are not. This EC will wait until *all* elements are visible which means it will timeout. – JeffC Apr 30 '18 at 14:24