【问题标题】:How to extract css values from website page如何从网站页面中提取css值
【发布时间】:2020-04-28 07:23:27
【问题描述】:

有没有办法使用 css 类名从网站页面中提取 css 值。我想使用父类 css 名称获取所有 css 值和子类值。

举个例子:

网页CSS:

.container {
    width: 80%;
  }
  .btn-wrap {
    padding: 3px;
    width: 25%;
    text-align: center;
  }
  .text-box {
    margin: 0 auto;
    width: 50%;
  }
  .frm-btn-grp {
    padding: 3px;
    width: 100%;
    text-align: center;

  .btn-success {
    border: 1px solid green;
    padding: 7px 24px;
    border-radius: 2px;
    color: white;
    background-color: green;
    width: 100px;
  }
  }

如果我将 .frm-btn-grp 作为输入,它将返回

.frm-btn-grp {
    padding: 3px;
    width: 100%;
    text-align: center;

  .btn-success {
    border: 1px solid green;
    padding: 7px 24px;
    border-radius: 2px;
    color: white;
    background-color: green;
    width: 100px;
   }
  }

这可能吗?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 好奇心胜过一切……你为什么要这样做?
  • @roganjosh 现在我想手动提取所有 css 值。这需要更多时间。所以我会看一些自动化代码。有可能吗?
  • 这重申了what你想做什么,但我问为什么
  • @Bryan 我什么都没开始。我已经搜索过相关但我仍然不知道如何开始这个想法。这就是我发布这个问题的原因。

标签: javascript python css web-scraping


【解决方案1】:

这是一些网络抓取操作:

import re
import urllib.request as ureq

sample_url = "https://stackoverflow.com/questions/59685137/how-to-extract-css-values-from-website-page"

with ureq.urlopen(sample_url) as req:
    data = req.read().decode('utf-8')

#- Split HTML by line ending; Look for 'text/css' matches
css_lines = [i.strip() for i in data.split('\n') if len(i) > 0 and 'text/css' in i]

#-- Create a simple regular expression to extract the css html
#-- Note: ?P<named_tag> allows for naming each section, but I think
#-- it only works on compiled regular expresions, which isn't a huge
#-- deal.
css_pat = r'href="(?P<css_url>.+)"'
p = re.compile(css_pat)

#-- Create a list and append it with our matches.
css_urls = []
for i in css_lines:
    tmp = p.search(i).group('css_url')
    if tmp:
        css_urls.append(tmp)

输出:

In[4]: css_urls
Out[4]: 
['https://cdn.sstatic.net/Shared/stacks.css?v=d0797a2dd6f2',
 'https://cdn.sstatic.net/Sites/stackoverflow/primary.css?v=f7becef1b212']

然后,你可以做任何事情。迭代 url 以获取所有 css 数据,打开并将所有 css 文件合并为一个,等等。

with ureq.urlopen(css_urls[0]) as req:
    css_data = req.read().decode('utf-8')

#-- Here's a sample printout of a css file for this page
#-- I added some .replace() statments to make it prettier :-)
print(css_data[:500]
    .replace(',', ',\n')
    .replace('{', ' {\n\t')
    .replace(';', ';\n\t')
    .replace('}','\n\t}\n\n')
    )

截断输出:

html,
body,
div,
span,
{...}
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
        margin:0;
        padding:0;
        border:0;
        font:inherit;
        font-size:100%;
        vertical-align:baseline
        }

article,
a

【讨论】:

    猜你喜欢
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    相关资源
    最近更新 更多