我有一個問題,我可以通過顯式等待來解決。我的好奇心來了,當我使用 300 秒時,selenium webdriver 內部發生了什么implicitly wait,它確實繼續提供過時的元素參考,但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 是什么?
uj5u.com熱心網友回復:
通過導航到所有由 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 秒。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527463.html
標籤:硒硒网络驱动程序网络驱动程序等待明确的陈旧元素引用异常
上一篇:python中的ChromeDriverManager()未檢測到options引數
下一篇:如何在Selenium、python中單擊此按鈕。每次我點擊它,它的鏈接都會改變,所以我不能輸入一個特定的鏈接來點擊
