【问题标题】:stale element refernce issue and dom refreshing via explicit/implicit waits过时的元素引用问题和通过显式/隐式等待刷新 dom
【发布时间】:2022-11-04 18:44:33
【问题描述】:

我有一个问题,我可以通过显式等待来解决。我的好奇心来了,当我使用implicitly wait 300 秒时,selenium webdriver 内部发生了什么,它确实继续提供过时的元素引用,但explicit wait with timeout 77sec 它可以正常工作。 我的代码在下面

for i in range(len(x_indexes)):
    x_indexes = wait.until(EC.visibility_of_all_elements_located((By.XPATH, '//div[@data-asin]')))#--here i added explicit wait
    x_data_asin=x_indexes[i].get_attribute('data-asin')#on this line error stale ref was occuring
    if x_data_asin!="":
        
        #clicking to each item for getting iban values ->back page
        a_href_element_of_index=x_block_of_index.find_element(By.XPATH,'.//h2/a')

        a_href_element_of_index.click()
        a_isbn_element=driver.find_element(By.XPATH,'//span[contains(text(),"ISBN")]')
        x_isbn_element_parent=a_isbn_element.find_element(By.XPATH,'..')
        print(x_isbn_element_parent.get_attribute('textContent'))
        #driver.back()
        driver.execute_script('window.history.go(-1)')
        print(a_href_element_of_index,'a',sep='-->')
        #driver.implicitly_wait(300)
        --loop ends

当我在 x_indexes 中循环每个项目时,我单击每个锚元素,页面指向另一个页面,在那里我提取我想要的数据,然后driver.back 或driver.execute_script('window.history.go(-1)') 将我带回到以相同方式继续迭代的页面。我有过时的引用,该元素未附加到页面,我尝试在循环结束行后隐式等待 300。结果是同样的错误。因此,当我尝试明确等待 wait=WebDriverWait(driver,timeout=77) 时,错误停止发生。 我想知道等待 300 秒和 77 背后的逻辑背后的 webdriver 是什么?

【问题讨论】:

    标签: selenium selenium-webdriver webdriverwait explicit staleelementreferenceexception


    【解决方案1】:

    通过导航到所有由 Selenium Web 元素收集的另一个页面(它们实际上是对物理 Web 元素的引用)变得不再有效,因为当您再次打开该网页时会重新构建它。
    现在,driver.implicitly_wait 正在为find_element 和find_elements 方法设置超时,仅根据给定的定位器搜索元素。默认implicitly_wait 设置为0。这意味着如果没有立即在页面上找到元素,Selenium 将抛出异常。通过将implicitly_wait 设置为另一个值,它将继续搜索该元素,直到找到它或超时,即第一个。
    但是,如果您正在迭代,这将无济于事现存的以前收集的元素列表x_indexes,因为这些引用现在不再相关,因为网页被重新渲染,如前所述。
    但是,如果您使用x_indexes = wait.until(EC.visibility_of_all_elements_located((By.XPATH, '//div[@data-asin]'))),这将在主页上等待,如果您从最近打开的链接返回到这些元素的可见性,再次收集列表,然后您将能够单击下一个元素。
    此外,通常不需要将 implicitly_wait 或 WebDriverWait 设置为超过 20-30 秒。

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多