【问题标题】:Extract backgroud url on <style> tag by Scrapy通过 Scrapy 提取 <style> 标签上的背景 url
【发布时间】:2020-08-10 19:04:24
【问题描述】:

我正在尝试通过 Scarpy scrape 标记样式:

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

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

我试图找到我的答案,但我什么也没找到。 非常感谢

【问题讨论】:

  • 显示您的代码?你是怎么尝试的?
  • response.xpath("//div[@id='main_container']/@style").get() 但我知道这是不正确的,因为它不会在scrapy shell上返回跨度>
  • 您不会以这种方式获得它,因为在您的情况下,style 不是位于body 中的 HTML 节点的属性,而是在 head 中声明的 CSS 属性。你可以试试看this ticket
  • 它很脏,但您可以使用内联 css 添加背景并通过 javascript 访问它
  • @Hisato 但我想废弃一个网站如何添加?

标签: css python-3.x web-scraping scrapy


【解决方案1】:

我尝试通过 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)

【讨论】:

    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 2015-03-05
    • 2019-11-26
    相关资源
    最近更新 更多