[英]How can I use python to change css attributes of an html document?
我有一个包含许多HTML文档的目录。 其中大多数包含代码块
.org-link {
/* org-link */
color: #b58900;
font-weight: bold;
text-decoration: underline;
}
在<style type="text/css">
标记内。 我想编写一个删除行text-decoration: underline;
的脚本text-decoration: underline;
并在每个文件中将此颜色从该块更改为#2aa198
。
是否可以使用python完成此操作?
您可以使用正则表达式进行必要的替换,如下所示:
import re
test = """
.org-link {
/* org-link */
color: #b58900;
font-weight: bold;
text-decoration: underline;
}
"""
def fix(org_link):
new_color = re.sub(r'(.*?color\s*?:\s*?)(.*?)(;)', r'\1#777\3', org_link.group(0), flags=re.S)
return re.sub(r'(.*?)(\s+?text-decoration: underline;)(.*?)', r'\1\3', new_color, flags=re.S)
print re.sub(r'(org-link\s+\{.*\})', fix, test, flags=re.S)
这将转换文本如下:
.org-link {
/* org-link */
color:#777;
font-weight: bold;
}
它的工作方式是首先确定合适的org-link
块,然后先替换颜色,然后删除所有text-decoration
条目。
然后可以将该脚本扩展为在给定文件夹中的所有HTML文件上执行此操作,如下所示:
import re
import glob
def fix(org_link):
new_color = re.sub(r'(.*?color\s*?:\s*?)(.*?)(;)', r'\1#777\3', org_link.group(0), flags=re.S)
return re.sub(r'(.*?)(\s+?text-decoration: underline;)(.*?)', r'\1\3', new_color, flags=re.S)
for html_file in glob.glob('*.html'):
print html_file
with open(html_file) as f_input:
html = re.sub(r'(org-link\s+\{.*\})', fix, f_input.read(), flags=re.S)
with open(html_file, 'w') as f_output:
f_output.write(html)
使用Python 2.7.9测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.