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

