首页 > 解决方案 > 图片库中 15 个元素后的 StaleElementReferenceException

问题描述

我正在尝试从我的网站获取图片链接,它有大约 40 张图片,我正在使用driver.find_elements_by_css_selector将所有图片添加到列表中。

当我遍历这个列表并打印这些图像的 id 时,对于前 15 张图像,它在抛出之后的一切都运行良好StaleElementReferenceException

我正在使用WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'image-list')))加载我的图片库。

我该如何解决这个问题StaleElementReferenceException

谢谢。

标签: pythonseleniumautomated-tests

解决方案


我相信保存图像的容器会动态加载它们,因此您必须使用以下逻辑。

# load the images in the dynamic list container
driver.find_element_by_xpath("(//*[@id='image-list']//img)[last()]").location_once_scrolled_into_view
time.sleep(1)
driver.find_element_by_xpath("(//*[@id='image-list']//img)[last()]").location_once_scrolled_into_view
time.sleep(1)
#get number of images
images = driver.find_elements_by_xpath("//*[@id='image-list']//img")
# use the for loop
for imageNum in range(len(images)):
    # access the image here
    image = driver.find_element_by_xpath("(//*[@id='image-list']//img[)" + str(imageNum+1) + "]")
    # now you can use the image element (first scroll to element)
    image.location_once_scrolled_into_view
    # get the image link here
    print(image.get_attribute('src'))

推荐阅读