Selenium Python-为什么StaleElementReferenceException而不是NoSuchEl



我正在编写一段自动登录过程的代码。这个过程包括在第一个页面上填写用户名,单击一个按钮,然后进入第二个页面,在那里我将填写pw并按下第二个按钮。该网页有时会看到大量流量,并在点击第一页后发出"稍后再试…"的消息。为了解决这个问题,我设置了一个循环,不断点击,直到我们进入下一页。

一旦我读完下一页,我仍然处于while循环中。然而,我原以为寻找"稍后重试"消息会产生NoSuchElementException并因此中断循环,但我得到了StaleElementReferenceException。我知道,因为我转到了另一个页面,所以这个"稍后再试"元素不再在DOM中。

为什么引发StaleElementReferenceException而不是NoSuchElementException如果网页上的流量很低,则不会生成"稍后重试"消息,并且except NoSuchElementException会打破循环。只要消息出现一次,StaleElement。Selenium是否跟踪元素的引用,即使我们不将它们存储在变量中?如果是,我们如何删除它?

我最初尝试了除StaleElementReferenceException之外的来捕获此异常。但什么也没发生。代码最终点击进入下一页,但继续运行循环,在StaleElementReferenceException上中断(第4行(如何捕获此异常我看过所有相关的问题,但没有找到有效的答案。

EDIT 1我知道在SO上发现了不同的例子,人们使用except StaleElementReferenceException:。但是,它在下面的代码中不起作用。代码一直循环,直到它成功地传递到下一页,但随后中断了陈旧元素异常。

while True:
try:
#looking for "try again later" message
WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, "//[@id='uiview']/ui-view/div/div[1]/div[1]/ui-view/div/div[2]/div/div[2]/form/div[3]/p")))
#if it finds the element it clicks the login button.
login_butn_1.click()
print("clicked")
#if logging in works; no "try again later" element, so we can break the loop
except NoSuchElementException:
print("no such element")
break
#Sometimes loading time is too long for "try again later"... message too appear and locating that element times out
#Need to reselect the button to be able to click it
except TimeoutException:           
webdriver.ActionChains(self.driver).move_to_element(login_butn_1).click(login_butn_1).perform()
print("time out")
except StaleElementReferenceException:
print("stale element exception")
break

Stale意味着陈旧、腐朽、不再新鲜。Stale Element的意思是旧的元素或不再可用的元素。假设有一个元素在WebDriver中被引用为WebElement的网页上找到。如果DOM发生更改,那么WebElement就会过时。如果我们尝试与过时的元素交互,然后引发了StaleElementReferenceException。

这是正常的,当我记得500ms时,默认情况下轮询元素状态时,可能会发生这种情况。您也可以在您的情况下添加它,就像逻辑上"元素不在DOM中"意味着不存在一样。或者添加额外的等待,因为几毫秒内就可以刷新并出现。

尝试添加额外的等待,或者将其放入Try{}catch{},然后刷新元素,这意味着尝试再次初始化它element = driver.find_element(By.XPATH, '//[@id='uiview']/ui-view/div/div[1]/div[1]/ui-view/div/div[2]/div/div[2]/form/div[3]/p"]')

元素刷新钞票会引发异常

最新更新