好了伙计们..。我知道这个问题以前似乎得到了回答,但我尝试过几种解决办法,但都没有奏效。如果我再见到StaleElementReferenceException,我就会失去它。我妻子的男朋友在嘲笑我,请帮帮忙。
编辑:删除了一些代码,因为我认为它已经不再相关,以努力压缩这篇文章。
更新:来自@vitaliis建议如下,我将代码更改为:
while True:
xpath_atc = '//div[@class="fulfillment-add-to-cart-button"]'
try:
wait = WebDriverWait(self.driver, 60)
wait.until(EC.visibility_of_all_elements_located((By.XPATH, xpath_atc)))
except TimeoutException:
print(f'A timeout occured after 60s. Refreshing page and trying again...')
self.driver.refresh()
continue
element_arr = self.driver.find_elements_by_xpath(xpath_atc)
for i in range(len(element_arr)):
wait.until(EC.visibility_of(element_arr[i]))
if element_arr[i].text == 'Add to Cart':
element_arr[i].click()
return
time.sleep(30)
self.driver.refresh()现在,这段代码似乎是我迄今尝试过的最有效的代码,因为它产生了较少的StaleElementReferenceException,但是它仍然产生它们.
我非常困惑,它不一致,有时例外发生,有时它没有。任何其他关于这个问题的想法将不胜感激。
解决方案: tldr;这是可行的
element = self.driver.find_element_by_xpath(xpath)
while(EC.staleness_of(disc_ele).__call__(False)):
element = self.driver.find_element_by_xpath(xpath)
text = element.text如果有人对此感兴趣,我会给出最好的猜测。staleness_of类定义如下:
class staleness_of(object):
""" Wait until an element is no longer attached to the DOM.
element is the element to wait for.
returns False if the element is still attached to the DOM, true otherwise.
"""
def __init__(self, element):
self.element = element
def __call__(self, ignored):
try:
# Calling any method forces a staleness check
self.element.is_enabled()
return False
except StaleElementReferenceException:
return True当与WebDriverWait类一起使用时,即WebDriverWait(driver, timeout).until(EC.staleness_of(element)),我们正在等待元素变得陈旧,这就是我们要寻找的,对吗?嗯,由于陈旧异常的不一致性,元素可能不会过时,如果它不过时,那么我们将得到一个超时异常,这不是期望的结果。
幸运的是,staleness_of类有一个方法__call__(),如果元素陈旧,否则返回__call__()。因此,使用while循环,我们可以通过每次迭代更新元素并使用更新后的元素上的__call__()方法来检查元素是否陈旧。最后,更新的元素不会过时,__call__()方法将返回false退出循环。
编辑: Welp,不工作。我想有一种情况是,元素在while循环条件下不过时,但在调用.text时却变得陈旧。
发布于 2021-04-03 01:18:44
你的定位器是独一无二的吗?试着等到元素可点击时:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable(
(By.XPATH, '//div[@class="fulfillment-add-to-cart-button"]')))
button = driver.find_element_by_xpath('//div[@class="fulfillment-add-to-cart-button"]')
button.click()如果有多个元素具有相同的定位器,请尝试visibility_of_all_elements_located而不是element_to_be_clickable
我可以提出以下算法:
find_elements_by_xpath在循环中查找具有相同定位器https://stackoverflow.com/questions/66926485
复制相似问题