【发布时间】:2019-07-10 23:34:43
【问题描述】:
我知道,这似乎是一个简单的问题,但请阅读我的问题。
我想提取符合以下模式的 html 类名:
regex = re.compile(r'([\w-]+)-([#\w\d,%()\.]+)')
并将其作为 CSS 样式写入不同的文件中。
为此,我有一本我们将要使用的值和属性的字典:
keyword = {
'c':'color',
'bg':'background',
'red':'#ed1a1a',
'blue':'#60a8ff'
#etc
}
示例:
html 文件:<div class="c-red bg-blue"> content </div>
css 文件中的输出:
.c-red{
color: red;
}
.bg-blue{
background: blue;
}
这是我的脚本,基本上可以做到这一点:
regex = re.compile(r'([\w-]+)-([#\w\d,%()\.]+)')
with open('index.html', 'r') as file:
with open('style.css', 'a+') as newfile:
lines = file.readlines()
for line in lines:
if 'class="' in line:
to_replace = regex.findall(line)
for key in to_replace:
prop=key[0]
value=key[1]
name='.'+prop+'-'+value
if prop and value in keyword:
var1 =('\n'+name+'{'+
'\n'+keyword[prop]+': '+
keyword[value]+';'+
'\n'+'}')
newfile.write(var1)
但是 如果我有多个相似的 HTML 字符串,例如:
<div class="c-red bg-blue"> content </div>
<div class="c-red bg-blue"> content2 </div>
<div class="c-red bg-blue"> content2 </div>
脚本将编写与 HTML 文件中的字符串一样多的 CSS 命令。
如何防止这种重复?
我试过了:
var1=''
和
if var1 in newfile:
break
else:
newfile.write(var1)
但这些都不起作用。
【问题讨论】:
-
你知道BeatyfulSoup吗?
-
问题出在
if var1 in newfile:newfile 不是新文件的内容。如果你想要内容,你必须阅读这个文件。 -
@Matej 是的,我在
a+模式下尝试过。 -
只需将 var1s 存储在一个集合或其他东西中,然后在写入之前检查它们是否存在。
-
@valeria 是的,没错,但你必须阅读这个文件,比如
if var1 in newfile.read(),但它不是很有效。
标签: python regex web-scraping