2015-02-04 2 views
0

lxml을 사용하여 src 컨텐츠를 가져 와서 공백으로 바꾸고 싶습니다.
하지만 신체는 여전히 교체되지 않습니다. 도와주세요. 감사합니다. 예를 들어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

는 적어도, 당신은 body에 교체의 결과를 할당해야 :

for ss in src: 
    body = body.replace(str(ss), '') 
print body 

비록 개인적으로이 방법이 마음에 들지 않습니다.

for element in doc.xpath("//*[@src]"): 
    element.attrib['src'] = '' 

print lxml.html.tostring(doc) 
+0

감사합니다 : 더 나은 src 속성이 있고 빈 문자열로 속성 값을 설정 모든 태그를 찾을 수 있습니다! 네 말이 맞다. 그리고 코드가 아주 아름답다. – user2492364