问题
Using python how can I get the background image using selenium? Which has an inline CSS? I want to get the image URL from the background-image: url()
<div id="pic" class="pic" data-type="image" style=" background-image: url(http://test.com/images/image.png;); height: 306px; background-size: cover;"></div>
回答1:
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:
- Retrieving the background in How to convert #ffffff to #fff or #fff to #ffffff while asserting the background color rgb(255,255,255) returned by Selenium getCssValue("background")
- Retrieving a sub-string in How to retrieve a sub-string from a string that changes dynamically with respect to multiple delimiters through Selenium in Python
回答2:
Try This:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.pic#pic[data-type='image']"))).get_attribute("href"))
回答3:
To get the URL
You need to use regular expression
.
In order to use regular expression Import re
and then use the following regular expression.
import re
itemimage=WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div#pic"))).value_of_css_property("background-image")
print(re.search("(?P<url>http?://[^\s;]+)", itemimage).group("url"))
Output:
http://test.com/images/image.png
来源:https://stackoverflow.com/questions/59103063/how-to-get-background-image-from-inline-css-using-selenium