假设我有html代码。它被破坏了(它是从另一个程序给出的)。我必须找到其中的所有图像,并将src属性更改为一些代码。仅此而已,它应该在决赛中被打破。在
这是我的代码:# -*- coding: utf-8 -*-
from lxml import etree
from StringIO import StringIO
def test(text):
text = analyze_dir_template_imgs(text)
return text
def analyze_dir_template_imgs(text):
ts = [
{
'name':'img',
'path':"//img[@src]",
'attrib': 'src',
},
]
parser = etree.HTMLParser()
for t in ts:
tree = etree.parse(StringIO(text), parser)
path = t['path']
name = t['name']
attrib = t.get('attrib', False)
text = str_repr(tree.getroot())
#text_to_file(text, 'temp/template_dir.html', 0, 'wb')
links = tree.xpath(path)
i = 0
for l in links:
i+=1
#print l
y0 = l.attrib[attrib]
print y0
x0 = str_repr(l)
if name=='img':
repl_to = '[image]'
x0_new = x0.replace(y0, repl_to)
text = text.replace(x0, x0_new)
print text
return text
def str_repr(el, enc='utf-8'):
text = etree.tostring(el, pretty_print=True, method='xml', encoding=enc)
return text
if __name__ == "__main__":
text = u'''
[[body]]
test(text)
但问题是在这个过程中lxml会更正html代码。我的意思是结果是
^{pr2}$
但我的结果应该从[name]
因为它是初始代码的开始。在
因为这是我的另一个错误的代码集,这是因为我的新代码只会更改。在
另一个问题是y0 = l.attrib[attrib]给出了/[[template]]/image.jpg,但是x0 = str_repr(l)给出了{}-正如你看到的那样,[被改成了/%5B,但我想得到的这一部分与原始html代码中的一样。在
如何正确使用lxml解决这个问题?谢谢。在
more...