dazai
dazai

Reputation: 716

Code iterating over the same element in Selenium when it should be over all the elements

I'm trying to get the title of the elements in my for loop but the result is a list of the title of the first element so the loop is not working. How can I fix it? I'm not sure what's causing this.

This is the code:

titles = []
wait = WebDriverWait(driver, 30)
elem = wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "thumbImage.loaded")))
for e in elem:
    ActionChains(driver).move_to_element(e).click().perform()
    e_title = wait.until(EC.visibility_of_element_located((By.CLASS_NAME,'titleOfElement'))).
    titles.append(e_title.text)

This is the HTML of the title:

<h2 id="detailsModal" class="titleOfElement"> title </h2>

Upvotes: 0

Views: 52

Answers (1)

Jortega
Jortega

Reputation: 3790

This issue might be that wait.until(EC.visibility_of_element_located((By.CLASS_NAME,'titleOfElement'))) is returning the first element it finds the number of times for e in elem: goes through the loop.

I am assuming you are instead trying to select the elements under the node e in the loop. For this you can use a relative path reference ./

Without access to site you are trying to do this on I am blind here but see below may get you in the right direction.

titles = []
wait = WebDriverWait(driver, 30)
elem = wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "thumbImage.loaded")))
for e in elem:
    ActionChains(driver).move_to_element(e).click().perform()
    # e_title = wait.until(EC.visibility_of_element_located((By.CLASS_NAME,'titleOfElement')))
    wait.until(EC.visibility_of_element_located((By.XPATH, "//h2[@class='titleOfElement']")))
    e_title = e.find_element_by_xpath(".//h2[@class='titleOfElement']")
    titles.append(e_title.text)

Upvotes: 1

Related Questions