你需要重构你的代码。您的代码模式可能是这样的(当然有不同的 id-s,但由于您没有包含您的代码或页面源,这是我能提供的最好的):
container = driver.find_elements_by_xpath('//*[@class="window_of_elements"]')
elements = container.find_elements_by_xpath('//*[@class="my_selected_class"]')
for e in elements:
minus_part = e.find_element_by_xpath('//span[@class="remove"]')
minus_part.click()
当您单击 时minus_part
,您的容器elements
可能会重新渲染/重新加载,并且您之前找到的所有元素都会变为stale
.
要绕过这个,你应该尝试不同的方法:
container = driver.find_elements_by_xpath('//*[@class="window_of_elements"]')
to_be_removed_count = len(container.find_elements_by_xpath('//*[@class="my_selected_class"]'))
for _ in range(to_be_removed_count):
target_element = container.find_element_by_xpath('//*[@class="window_of_elements"]//*[@class="my_selected_class"]')
minus_part = target_element.find_element_by_xpath('//span[@class="remove"]')
minus_part.click()
所以基本上你应该:
- 找出你应该找到多少被点击的元素
- 在 for 循环中找到并一一单击它们