Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

python - Using selenium webdriver to wait the attribute of element to change value

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')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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

Usage:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...