0

Is there a more efficient way of reading classes with the same name, rather than doing what im doing, i basically go through a code with index, because they all have the same name, is there a better way if selecting elements with the same class name, rather than the way i am doing it

Z = len(driver.find_elements_by_class_name('Class_With_Names'))

for x in range(Z):

x += 1

thisClass = driver.find_element_by_xpath(f"//ul[@class='same_name']/div[{str(x)}]")
classText = thisClass.find_element_by_class_name("class_with_text")

print(classText.text)
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

2 Answers2

0

Have you tried using the find_elements_by_xpath? This will return all of the elements with that class name.

Your code looks like it is incrementing after the div though? Are you just looking for information on all of the classes or to loop through the divs?

sjuice10
  • 29
  • 5
  • well that does work, but when each of those elements have a text, it doesnt print all of the text, gives me some sort of list error – ExoticLegend714 Jan 22 '21 at 03:54
0

Avoiding the index you can use the following Locator Strategy:

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 css_selector and get_attribute("innerHTML"):

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

    print([my_elem.text for my_elem in driver.find_elements_by_xpath("//ul[@class='same_name']//div")])
    

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

  • 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, "ul.same_name div")))])
    
  • 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, "//ul[@class='same_name']//div")))])
    
  • 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