Create custom wait until condition in Python

后端 未结 4 1858
失恋的感觉
失恋的感觉 2021-01-04 09:39

I tried to create a function with custom wait condition in Python. However, I get an error:

TypeError: \'bool\' object is not callable

4条回答
  •  甜味超标
    2021-01-04 10:19

    WebDriverWait(driver, 10).until() accepts a callable object which will accept an instance of a webdriver (driver is our example) as an argument. The simplest custom wait, which expects to see 2 elements, will look like

    WebDriverWait(driver, 10).until(
        lambda wd: len(wd.find_elements(By.XPATH, 'an xpath')) == 2
    )
    

    The waittest function has to be rewritten as:

    class waittest:
        def __init__(self, locator, attr, value):
            self._locator = locator
            self._attribute = attr
            self._attribute_value = value
    
        def __call__(self, driver):
            element = driver.find_element_by_xpath(self._locator)
            if element.get_attribute(self._attribute) == self._attribute_value:
                return element
            else:
                return False
    

    And then it can be used as

    element = WebDriverWait(driver, 10).until(
        waittest('//div[@id="text"]', "myCSSClass", "false")
    )
    

提交回复
热议问题