【问题标题】:Stale element reference: element is not attached to the page document when looping through pages过时的元素引用:循环浏览页面时元素未附加到页面文档
【发布时间】:2019-05-03 16:23:47
【问题描述】:

我正在尝试浏览目录中的每个产品并打印产品图片链接。以下是我的代码。

product_links = driver.find_elements_by_css_selector(".product-link")
for link in product_links:
    driver.get(link.get_attribute("href"))
    images = driver.find_elements_by_css_selector("#gallery img")
    for image in images:
        print(image.get_attribute("src"))
    driver.back()

但我收到错误selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document,我认为这是因为当我们返回目录页面时,页面再次加载,product_links 中的元素引用变得陈旧。

我们如何避免这个问题?有没有更好的解决方案?

【问题讨论】:

标签: python selenium-webdriver automated-tests


【解决方案1】:

我遇到了类似的问题,下面是我的解决方法。基本上,每次返回页面都必须刷新页面并重新建立链接列表。当然,这样做你不能使用for循环,因为你的对象每次都是陈旧的。

很遗憾,我无法对此进行测试,因为我无法访问您的实际网址,但这应该很接近

def get_prod_page(link):
    driver.get(link.get_attribute("href"))
    images = driver.find_elements_by_css_selector("#gallery img")
    for image in images:
        print(image.get_attribute("src"))
    driver.back()

counter=0
link_count= len(driver.find_elements_by_css_selector(".product-link"))
while counter <= link_count:
    product_links = driver.find_elements_by_css_selector(".product-link")[counter:]
    get_prod_page(product_links[0])
    counter+=1
    driver.refresh()

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多