【发布时间】:2014-11-05 15:19:58
【问题描述】:
我有两个输入文件:一个 html 文件和一个 css 文件。我想根据css文件的内容对html文件进行一些操作。
我的html是这样的:
<html>
<head>
<title></title>
</head>
<body>
<p class = "cl1" id = "id1"> <span id = "span1"> blabla</span> </p>
<p class = "cl2" id = "id2"> <span id = "span2"> blablabla</span> <span id = "span3"> qwqwqw </span> </p>
</body>
</html>
span id 的样式在 css 文件中定义(每个 span id 单独定义!)
在做真正的事情之前(根据他们的风格删除跨度),我试图从 html 中打印出 id,并从与每个 id 对应的 css 中打印出样式描述。
代码:
from lxml import etree
tree = etree.parse("file.html")
filein = "file.css"
def f1():
with open(filein, 'rU') as f:
for span in tree.iterfind('//span'):
for line in f:
if span and span.attrib.has_key('id'):
x = span.get('id')
if "af" not in x and x in line:
print x, line
def main():
f1()
所以,有两个 for 循环,如果分开,它们会完美地迭代,但是当放在这个函数中时,迭代会在第一个循环后停止:
>> span1 span`#span1 { font-weight: bold; font-size: 11.0pt; font-style: normal; letter-spacing: 0em }
我该如何解决这个问题?
【问题讨论】:
标签: python for-loop iteration lxml