You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python+re库匹配style.css中指定CSS类及其内容

用Python正则提取指定CSS类规则

目标需求

从给定的style.css文件中提取以下CSS选择器及其对应的属性内容:

  • .wallpaper .is-fullwidth
  • .wallpapers
  • .wallpaper
  • .content
  • .side
  • .about
  • .raf

实现代码

import re

# 读取CSS文件内容
with open('style.css', 'r', encoding='utf-8') as f:
    css_content = f.read()

# 指定要提取的目标选择器
target_selectors = [
    '.wallpaper .is-fullwidth',
    '.wallpapers',
    '.wallpaper',
    '.content',
    '.side',
    '.about',
    '.raf'
]

# 构建正则表达式:匹配目标选择器对应的规则块
# re.escape处理选择器中的特殊字符,re.DOTALL让.匹配换行符
pattern = re.compile(
    rf'({"|".join(re.escape(sel) for sel in target_selectors)})\s*\{{\s*(.*?)\s*\}}',
    re.DOTALL
)

# 查找所有匹配的规则块
matches = pattern.findall(css_content)

# 整理并输出结果
for selector, properties in matches:
    print(f"{selector} {{")
    print(f"    {properties.replace(';\n', ';\n    ')}")
    print("}\n")

# 如果需要保存到文件
with open('extracted_styles.css', 'w', encoding='utf-8') as f:
    for selector, properties in matches:
        f.write(f"{selector} {{\n    {properties.replace(';\n', ';\n    ')}\n}}\n\n")

代码说明

  1. 读取文件:通过open()读取style.css的全部文本内容。
  2. 正则构建:
    • 用re.escape()处理选择器中的特殊字符(如空格、点号),避免触发正则语法冲突。
    • \s*\{{匹配选择器后的左大括号及前后可能存在的空格、换行。
    • (.*?)以非贪婪模式匹配大括号内的所有属性内容,re.DOTALL参数确保匹配跨多行的内容。
    • \s*\}}匹配右大括号及前后的空格、换行。
  3. 结果处理:遍历匹配到的结果,格式化输出或保存到新文件,保持CSS代码的可读性。

提取结果示例

运行代码后,会输出格式化后的目标CSS规则:

.wallpaper .is-fullwidth {
    display: block;
    height: 100%;
    left: 0;
    top: 0;
    width: 100%;
}

.wallpapers {
    display: block;
}

.wallpaper {
    background-image: url("/statics/595865.jpg");
    background-position: center;
    background-size: cover;
    opacity: 0.1;
    position: fixed;
}

.content {
    display: flex;
    position: relative;
    min-height: 100vh;
}

.side {
    max-width: 23rem;
    max-height: 20rem;
}

.about {
    max-width: 26rem;
}

.raf {
 background-image: url("/statics/595865.jpg");
    background-position: center;
    background-size: cover;
    opacity: 0.1;
    position: fixed;
}

内容的提问来源于stack exchange,提问作者maryimana butom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:45:36