簡體   English   中英

如何從網站頁面中提取css值

[英]How to extract css values from website page

有什么方法可以使用 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;
   }
  }

這可能嗎?

這是一些網頁抓取操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM