Python Selenium:等到元素不再陈旧?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python Selenium:等到元素不再陈旧?相关的知识,希望对你有一定的参考价值。

我有一种情况,我想等到元素不再是STALE,即元素连接到DOM。以下等待选项无法以某种方式工作:

self.wait.until(EC.visibility_of_element_located((By.ID, "elementID")))
self.wait.until(EC.presence_of_element_located((By.ID, "elementID")))

它存在相反的等待函数,它等待一个元素变得陈旧,这是:

self.wait.until(EC.staleness_of((By.ID, "elementID")))

但我希望它等到元素不再长时间,即直到它连接到DOM。我该如何实现此功能?

编辑:这里有一个解决方案:here但我正在寻找任何其他更好的方法,如果有的话。

答案

来自documentation

陈旧性:

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

要点击的元素:

class element_to_be_clickable(object):
    """ An Expectation for checking an element is visible and enabled such that
    you can click it."""
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        element = visibility_of_element_located(self.locator)(driver)
        if element and element.is_enabled():
            return element
        else:
            return False

如您所见,两者都使用相同的方法is_enabled()来执行检查。

另一答案

陈旧元素是您存储的元素引用,它不再有效,因为页面,页面的一部分或者可能只是元素被刷新。一个简单的例子

element = driver.find_element_by_id("elementID")
# do something that refreshes the page
element.click()

这里element.click()将引发陈旧元素异常,因为引用在刷新之前存储但在刷新之后使用(单击)。在这种情况下,该引用不再有效。一旦引用过时,它就永远不会变得“无条件”......该引用永远不会再次使用。解决这个问题的唯一方法是再次存储引用。

注意:您的代码示例对.staleness_of()不正确。它需要一个Web元素引用,而不是一个定位器。您需要一个现有的引用来等待它过时。见the docs

现在要解决这个问题......你需要等待刷新完成然后获得一个新的引用。

element = driver.find_element_by_id("elementID")
# do something that refreshes the element
self.wait.until(EC.staleness_of(element))
element = self.wait.until(EC.visibility_of_element_located((By.ID, "elementID")))
# do something with element

等待元素变为陈旧等待元素引用丢失,这意味着元素已更改/刷新。一旦我们知道元素已经改变,我们现在可以得到一个新的引用。在这种情况下,等待元素变得可见。我们现在有一个新的引用存储在我们的变量中,我们可以使用它而不会过时的元素异常。

另一答案
WebDriverWait(browser, waitTime).until(EC.presence_of_element_located(
                (By.XPATH or By.id or w/e you want, " xpath or id name")))
另一答案

因为你想在WebElement不再陈旧时拿起text属性,你可以使用以下内容:

wait1 = WebDriverWait(driver, 10)
wait1.until(expected_conditions.text_to_be_present_in_element((By.ID, "elementID"), "expected_text1"))

要么

wait2 = WebDriverWait(driver, 10)
wait2.until(expected_conditions.text_to_be_present_in_element_value((By.ID, "elementID"), "expected_text2"))

以上是关于Python Selenium:等到元素不再陈旧?的主要内容,如果未能解决你的问题,请参考以下文章

如何等到 Selenium 中不再存在元素

Python selenium:等到元素可点击 - 不工作

Python Selenium 2 API 并等待 DOM 准备好/元素可见

Selenium WebDriver 如何解决陈旧元素引用异常?

当我尝试使用for循环单击所有链接时,硒显示陈旧错误?

Python,Selenium:'元素不再附加到 DOM'