我在页面上有一组元素,看起来像:
<div class="course-lesson__course-wrapper" data-qa-level="z1">
<div class="course-lesson__course-title">
<section class="course-lesson__wrap" data-qa-lesson="trial">
<section class="course-lesson__wrap" data-qa-lesson="trial">
有几个页面采用这种布局。我想获得z1中所有元素的列表,如果是data-qa-lesson="trial"
,请单击它们
我有这个代码
#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)
但似乎不起作用
为了避免StaleElementException
,您可以尝试以下方法:
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)