【发布时间】:2014-11-21 17:53:21
【问题描述】:
我需要清理一个 html 文件,例如删除多余的“跨度”标签。如果“跨度”与 css 文件中字体粗细和字体样式的父节点格式相同(我将其转换为字典以便更快地查找),则“跨度”被认为是多余的。
html 文件如下所示:
<p class="Title">blablabla <span id = "xxxxx">bla</span> prprpr <span id = "yyyyy"> jj </span> </p>
<p class = "norm">blalbla <span id = "aaaa">ttt</span> sskkss <span id = "bbbbbb"> aa </span> </p>
我已经存入字典的 css 样式:
{'xxxxx':'font-weight: bold; font-size: 8.0pt; font-style: oblique',
'yyyyy':'font-weight: normal; font-size: 9.0pt; font-style: italic',
'aaaa': 'font-weight: bold; font-size: 9.0pt; font-style: italic',
'bbbbbb': 'font-weight: normal; font-size: 9.0pt; font-style: normal',
'Title': 'font-style: oblique; text-align: center; font-weight: bold',
'norm': 'font-style: normal; text-align: center; font-weight: normal'}
所以,鉴于<p Title> 和<span id xxxxx>,以及<p norm> 和<span bbbbbb> 在css 字典中的字体粗细和字体样式具有相同的格式,我想得到以下结果:
<p class= "Title">blablabla bla prprpr <span id = "yyyyy"> jj </span> </p>
<p class = "norm">blalbla <span id = "aaaa">ttt</span> sskkss aa </span> </p>
另外,我可以通过查看它们的 id 来删除一些跨度:如果它包含“af” - 我删除它们而不查看字典。
所以,在我的脚本中有:
from lxml import etree
from asteval import Interpreter
tree = etree.parse("filename.html")
aeval = Interpreter()
filedic = open('dic_file', 'rb')
fileread = filedic.read()
new_dic = aeval(fileread)
def no_af(tree):
for badspan in tree.xpath("//span[contains(@id, 'af')]"):
badspan.getparent().remove(badspan)
return tree
def no_normal():
no_af(tree)
for span in tree.xpath('.//span'):
span_id = span.xpath('@id')
for x in span_id:
if x in new_dic:
get_style = x
parent = span.getparent()
par_span =parent.xpath('@class')
if par_span:
for ID in par_span:
if ID in new_dic:
get_par_style = ID
if 'font-weight' in new_dic[get_par_style] and 'font-style' in new_dic[get_par_style]:
if 'font-weight' in new_dic[get_style] and 'font-style' in new_dic[get_style]:
if new_dic[get_par_style]['font-weight']==new_dic[get_style]['font-weight'] and new_dic[get_par_style]['font-style']==new_dic[get_style]['font-style']:
etree.strip_tags(parent, 'span')
print etree.tostring(tree, pretty_print =True, method = "html", encoding = "utf-8")
这会导致:
AttributeError: 'NoneType' object has no attribute 'xpath'
而且我知道正是“etree.strip_tags(parent, 'span')” 行导致了错误,因为当我将其注释掉并在任何其他行之后进行 print smth - 一切正常。
另外,我不确定使用这个 etree.strip_tags(parent, 'span') 是否能满足我的需要。如果在父级内部有几个具有不同格式的跨度怎么办。无论如何,这个命令会剥离所有这些跨度吗?我实际上只需要在“for span in tree.xpath('.//span'):”中剥离一个跨度,即当前的跨度,它是在函数的开头获取的。
我整天都在看这个错误,我觉得我忽略了一些东西......我非常需要你的帮助!
【问题讨论】:
-
这是在您的
span元素中滥用id属性。您可能会“在野外”找到它,但除非每个跨度都是唯一的,否则class是正确的说明符,而不是id。 -
每个 span 的 id 都是唯一的,尽管 p 中的类不是唯一的。
-
你一个对,应该是bbbbb!对不起((