我有以下 try 陳述句,它基本上找到了一個重置??我所在的當前頁面的按鈕。總而言之,頁面重新加載,
try:
reset_button = D.find_element(By.XPATH,"//button[starts-with(@class,'resetBtn rightActionBarBtn ng-star-inserted')]")
reset_button.click()
D.implicitly_wait(5)
ok_reset_botton = D.find_element(By.ID,'okButton')
D.implicitly_wait(5)
print(ok_reset_botton)
ok_reset_botton.click()
D.implicitly_wait(5)
# Trying to reset current worksheet
except:
pass
print(D.current_url)
grupao_ab = D.find_element(By.XPATH,'//descendant::div[@][1]')
D.implicitly_wait(5)
grupao_ab.click()
奇怪的是每次執行 try 陳述句時,我都會收到以下錯誤日志
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
根據日志,這發生在以下代碼行中
grupao_ab.click()
當我查看 selenium 給出的原因時,它說這是因為該元素不再在給定的 DOM 上,但是該元素grupao_ab甚至沒有在該頁面中定義,那么為什么它會給我這個錯誤?如果需要任何額外資訊,請發表評論。
uj5u.com熱心網友回復:
首先,StaleElementReferenceException意味著您嘗試訪問的 Web 元素參考不再有效。這通常發生在頁面重新加載后。這正是這里發生的事情。
發生的情況如下:您單擊了重置按鈕,然后立即收集grupao_ab元素,然后不久嘗試單擊它。grupao_ab但是在您找到元素的那一刻grupao_ab = D.find_element(By.XPATH,'//descendant::div[@][1]')和您嘗試單擊它的那一行之間,重新加載開始了。因此,之前收集的 Web 元素實際上是對 DOM 上的物理元素的參考,不再指向該 Web 元素。
你可以在這里做的是:點擊重繪 按鈕后設定一個短暫的延遲,以便重繪 開始,然后等待grupao_ab元素變為可點擊。WebDriverWait expected_conditions應該為此使用顯式等待。
此外,您應該了解這不是D.implicitly_wait(5)暫停命令。它設定超時和等待搜索元素存在的方法。通常我們根本不會設定這個超時,因為最好使用顯式等待,而不是隱式等待。而且你永遠不應該混合這兩種型別的等待。
即使您想設定某個值,通常也無需再次設定,此設定將應用于整個會話。
請嘗試更改您的代碼如下:find_elementfind_elementsWebDriverWait expected_conditionsimplicitly_waitimplicitly_waitdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 20)
try:
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[starts-with(@class,'resetBtn rightActionBarBtn ng-star-inserted')]"))).click()
wait.until(EC.element_to_be_clickable((By.ID, "okButton"))).click()
print(ok_reset_botton)
time.sleep(0.5) # a short pause to make reloading started
except:
pass
print(D.current_url)
#wait for the element on refreshed page to become clickable
wait.until(EC.element_to_be_clickable((By.XPATH, '//descendant::div[@][1]'))).click()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/531047.html
上一篇:需要在使用pythonselenium運行的打開的Web瀏覽器中將cookie添加到API標頭?
下一篇:Selenium無法獲取此類
