使用Selenium WebDriver等待元素的属性更改值 [英] Using selenium webdriver to wait the attribute of element to change value

查看:999
本文介绍了使用Selenium WebDriver等待元素的属性更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属性为"aria-busy"的元素,当进行数据搜索和处理时,该元素从true变为false.如果达到20秒并且属性未从true更改为false,我如何使用硒预期条件和显式等待来等待默认时间(例如20秒).抛出异常.我有关注者,但它确实不起作用

I have one element with attribute "aria-busy" that changes from true to false when data is in searching and done. How can I use selenium Expected Conditions and Explicit Waits to wait a default time like 20 seconds, if 20 seconds reaches and the attribute is not changed from true to false. throw exceptions. I have following, but it does not really work

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')

推荐答案

期望条件只是可调用,您可以将其定义为简单函数:

An Expected Condition is just a callable, you can define it as a simple function:

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__()魔术方法:

A bit more generic and modular, though, would be to follow the style of the built-in Expected Conditions and create a class with a overriden __call__() magic method:

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"))

这篇关于使用Selenium WebDriver等待元素的属性更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆