通过Scrapy提取<style>标签上的backgroud网址

问题描述

我正在尝试通过粗俗的方式删除标记样式:

<style>
 #main_container {
      background: #f50 url('https://google.com/sample.jpg') top center no-repeat;
    }
</style>

<div id="main_container">
   some text
</div>

我尝试找到答案,但未找到任何答案。 非常感谢

解决方法

我试图通过tinycss做到这一点,但是出现了错误,所以我改变了主意,通过cssutils BeautifulSoup解决了这个问题,在这里您可以看到更完整的源代码:

from bs4 import BeautifulSoup as BSoup
import cssutils
import string



image_adress=''
with open('/home/azimi/my.html') as webpage:
    html = webpage.read()
    soup = BSoup(html,'html.parser')
for styles in soup.select('style'):
    css = cssutils.parseString(styles.encode_contents())
    for rule in css:
        if rule.type == rule.STYLE_RULE:
            style = rule.selectorText
            if style == '#container_container':
                for item in rule.style:
                    propertyname = item.name
                    value = item.value
                    if propertyname == 'background':
                        back_vals = item.value.split(' ')
                        image_adress = back_vals[1]
                        print("Image :"+ image_adress)