使用Selenium WebDriver等待元素属性值的变化

7

我有一个带有属性 "aria-busy" 的元素,在搜索数据时会从 true 改变为 false。如何使用 selenium 中的“预期条件”和“显式等待”等待默认时间,例如 20 秒,如果 20 秒到了但属性未从 true 改变为 false,则抛出异常。我有以下代码,但它并不起作用。

import selenium.webdriver.support.ui as ui
from selenium.webdriver.support import expected_conditions as EC

<div id="xxx" role="combobox" aria-busy="false" /div>
class Ele:
    def __init__(self, driver, locator)
        self.wait = ui.WebDriverWait(driver, timeout=20)

    def waitEle(self):
        try:
            e = self.driver.find_element_by_xpath('//div[@id='xxxx']')
            self.wait.until(EC.element_selection_state_to_be((e.get_attribute('aria-busy'), 'true')))
        expect:
            raise Exception('wait timeout')
2个回答

9

预期条件只是一个可调用对象,你可以将其定义为一个简单的函数:

def not_busy(driver):
    try:
        element = driver.find_element_by_id("xxx")
    except NoSuchElementException:
        return False
    return element.get_attribute("aria-busy") == "false"

self.wait.until(not_busy)

更加通用和模块化的方式是按照内置的预期条件风格,创建一个具有重写__call__()魔法方法的class

from selenium.webdriver.support import expected_conditions as EC

class wait_for_the_attribute_value(object):
    def __init__(self, locator, attribute, value):
        self.locator = locator
        self.attribute = attribute
        self.value = value

    def __call__(self, driver):
        try:
            element_attribute = EC._find_element(driver, self.locator).get_attribute(self.attribute)
            return element_attribute == self.value
        except StaleElementReferenceException:
            return False

使用方法:

self.wait.until(wait_for_the_attribute_value((By.ID, "xxx"), "aria-busy", "false"))

2
另一种方法涉及使用自定义定位器检查属性值,其中您不仅会检查id,还会检查aria-busy属性值:
self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#xxx[aria-busy=false]")))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接