I have a group of elements on the page that looks like:
<div data-qa-level="z1">
<div >
<section data-qa-lesson="trial">
<section data-qa-lesson="trial">
There are several pages with this layout. I want to get a list of all the elements in z1 and then click on them if it is a data-qa-lesson="trial"
I have this code
#finds all the elements for z1 - ...etc
listofA1 = driver.find_element(By.CSS_SELECTOR, "div.course-lesson__course-wrapper:nth-child(1)")
for elemen in listofA1:
#checks for the attribute i need to see if it's clickable
elementcheck = elemen.getAttribute("data-qa-lesson")
if elementcheck == "objective":
elemen.click()
#do some stuff then go back to main and begin again on the next element
driver.get(home_link)
But it does not seem to work
CodePudding user response:
To avoid StaleElementException
you can try this approach:
count = len(driver.find_elements(By.XPATH, '//div[@data-qa-level="z1"]//div[@data-qa-level="trial"]')) # Get count of elements
for i in range(count):
driver.find_elements(By.XPATH, '//div[@data-qa-level="z1"]//div[@data-qa-level="trial"]')[i].click() # click current element
# Do what you need
driver.get(home_link)