如何使用硒从嵌入式CSS获取背景图像 [英] How to get background-image from inline css using selenium

查看:65
本文介绍了如何使用硒从嵌入式CSS获取背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python如何使用硒获取背景图像?哪个有内联CSS?我想从背景图片中获取图片网址:url()

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>

推荐答案

要获取背景图片,您需要使用定位器策略:

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:

  • 使用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])

  • 使用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
    

  • 随着url被双引号括起来,即"...",您可以使用以下解决方案:

    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

    这篇关于如何使用硒从嵌入式CSS获取背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆