我有两个输入文件:一个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,从css打印对应于每个id的样式描述
代码:
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 }
我怎样才能解决这个问题?你知道吗
如果如我所想,树已完全加载到内存中,则可以尝试反转循环。这样,您只需浏览文件
filein
一次:这是因为在第二个外循环开始之前,您已经读取了所有filein行。 要使其正常工作,您需要在filein上启动内部循环之前添加f.seek(0):
相关问题 更多 >
编程相关推荐