我想使用lxml获取src内容并用空格替换它们 但身体仍然没有被取代 请帮帮我谢谢。
import re
import lxml.html
#the content of source.log is a webpage source code I got by scrapy
with open("source.log", "r") as bb:
c_str = bb.read()
body = c_str.decode('utf-8')
doc = lxml.html.fromstring(body)
src = doc.xpath("//@src")
for ss in src:
re.search(ss,body)
body.replace(str(ss),'')
print body
例如: 如果身体是
'src="http://pic/1379181836.jpg"/><br>紅心<br></div><div>tel:12345678</div>' \
'src="http://pic/4447918.jpg"/>'
我想要的结果是:
'src=""/><br>紅心<br></div><div>tel:12345678</div>' \
'src=""/>'
答案 0 :(得分:0)
至少,您需要将替换结果分配给body
:
for ss in src:
body = body.replace(str(ss), '')
print body
尽管如此,我个人并不喜欢这种做法。更好地找到具有src
属性的所有标记,并将属性值设置为空字符串:
for element in doc.xpath("//*[@src]"):
element.attrib['src'] = ''
print lxml.html.tostring(doc)