我有以下代碼:
for button in buttons:
ActionChains(driver).move_to_element(button).perform()
time.sleep(2)
button.click()
time.sleep(2)
try:
wait_button.until(EC.presence_of_element_located((By.XPATH,'//div/h2')))
time.sleep(2)
name = driver.find_element_by_xpath('//div/h2').text
except:
wait_button.until(EC.presence_of_element_located((By.XPATH,'//span[@id="chat-header-title"]')))
time.sleep(2)
name = driver.find_element_by_xpath('//span[@id="chat-header-title"]').text
def pull_ul() -> list:
chat_frame = driver.find_element_by_xpath("//iframe[starts-with(@id, 'experience-container-')]")
driver.switch_to.frame(chat_frame)
wait_button.until(EC.presence_of_element_located((By.XPATH,'//ul[@aria-label="Chat content"]')))
the_ul =driver.find_element(By.XPATH,'//ul[@aria-label="Chat content"]')
new_lis =the_ul.find_elements(By.TAG_NAME,'li')
return new_lis
def pull_ul_again() -> list:
the_ul =driver.find_element(By.XPATH,'//ul[@aria-label="Chat content"]')
new_lis_2 =the_ul.find_elements(By.TAG_NAME,'li')
return new_lis_2
lis = pull_ul()
print(f"Archiving Chat with {name} ...\n")
print("this is len lis: ",len(lis), "for " name)
這是終端顯示的內容:

如您所見,代碼實際上確實超過了引發錯誤的行,這怎么可能?另外,為什么會發生這種情況,我多次成功運行代碼,突然它開始拋出以下錯誤?
uj5u.com熱心網友回復:
你正在做的回圈,
for button in buttons:
ActionChains(driver).move_to_element(button).perform()
...
導致您的StaleElementReferenceException因為在您擁有的內部driver.switch_to.frame(chat_frame),但您永遠不會切換回默認內容或父框架,這意味著您的按鈕將不存在于該級別,因此 Selenium 會拋出StaleElementReferenceException。如果您離開頁面導航也可能發生這種情況(這也可能發生取決于按鈕的點擊)。
如果您曾經切換框架或離開頁面,則必須重新找到元素才能與它們互動。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/497455.html
上一篇:XPATH:使用.find_elements_by_xpath為未知數量的xpath輸入值
下一篇:創建和編輯資料框
