0

Is there any way to get all the elements with a certain class and put into a list? for example:

<li class="Fruit">Apple</li>
<li class="Fruit">Orange</li>

I would like to put Apple and Orange in a list.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
TheBotlyNoob
  • 369
  • 5
  • 16

2 Answers2

1
  driver.find_elements_by_class_name("Fruit")

Find elements returns all elements that much the given criteria ,here the class name , it returns list

you can print the text as:

https://selenium-python.readthedocs.io/locating-elements.html

elems = driver.find_elements_by_class_name("Fruit")
for elem in elems:
    print(elem.text)

or

elemsText = [i.text for i in driver.find_elements_by_class_name("Fruit")]
print(elemsText]
PDHide
  • 18,113
  • 2
  • 31
  • 46
1

To extract and print the texts e.g. Apple, Orange, etc from all of the <li class="Fruit"> using Selenium and you can use either of the following Locator Strategies:

  • Using class_name and get_attribute("textContent"):

    print([my_elem.get_attribute("textContent") for my_elem in driver.find_elements_by_class_name("Fruit")])
    
  • Using css_selector and get_attribute("innerHTML"):

    print([my_elem.get_attribute("innerHTML") for my_elem in driver.find_elements_by_css_selector(".Fruit")])
    
  • Using xpath and text attribute:

    print([my_elem.text for my_elem in driver.find_elements_by_xpath("//*[@class='Fruit']")])
    

Ideally you need to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

  • Using CLASS_NAME and get_attribute("textContent"):

    print([my_elem.get_attribute("textContent") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "Fruit")))])
    
  • Using CSS_SELECTOR and get_attribute("innerHTML"):

    print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".Fruit")))])
    
  • Using XPATH and text attribute:

    print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='Fruit']")))])
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Outro

Link to useful documentation:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352