Home > database >  Selenium Python: Wait for backgroundColor of Element to be 'rgb(...)`
Selenium Python: Wait for backgroundColor of Element to be 'rgb(...)`

Time:11-06

Using Selenium and Python, how can we wait for a certain element with id foo to have a backgroundColor of "rgb(1, 2, 3)"?

So far, I think it should be something like this

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

expected_backgroundColor = EC.some_method((By.ID, "foo"))
WebDriverWait(self.driver, 15).until(expected_backgroundColor)

but not sure which EC method to use.

Any advice will help! Thanks!

CodePudding user response:

You can use presence_of_element_located or visibility_of_element_located methods for this. Let's see below example,

Expected element xPath:

//input[@id='rgb(1, 2, 3)']

Code:

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//input[@id='rgb(1, 2, 3)']')))

or

WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//input[@id='rgb(1, 2, 3)']')))

In Java, methods like attributeToBe, attributeContains and attributeNotToBeEmpty methods will be available but not sure whether these methods are available in Python or not.

Java example:

WebElement element = driver.findElement(By.xpath("xPath "));
wait.until(ExpectedConditions.attributeToBe(element, "id", "rgb(1, 2, 3)"));

CodePudding user response:

I would most likely use a custom wait function that runs a script on the client site to check the color.

Something like:

from selenium.webdriver.support.ui import WebDriverWait

def has_expected_color(driver):
    return driver.execute_script("return document.getElementById(‘myid’).style.backgroundColor === ‘0xfff’")

WebDriverWait(driver).until(has_expected_color)
  • Related