How to get background-image from inline css using selenium

To get the background image you need to use value_of_css_property(property_name) method and you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    import re
    
    my_property = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.pic#pic[data-type="image"]"))).value_of_css_property("background-image")
    print(re.split('[()]',my_property)[1])
    
  • Using XPATH:

    import re
    
    my_property = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class="pic" and @id='pic'][@data-type="image"]"))).value_of_css_property("background-image")
    print(re.split('[()]',my_property)[1])
    
  • Console Output:

    test.com/images/image.png
    

Update

As the url is getting wrapped up with in double quotes i.e. "..." you can use the following solution:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class="pic" and @id='pic'][@data-type="image"]"))).value_of_css_property("background-image").split('"')[1])

References

You can find a couple relevant discussions related to:

Leave a Comment