2011-09-07 283 views
2

我需要替换我的html页面的数据内容中的一些字符串。我不能直接使用替换函数,因为我只需要更改数据部分。它不应该修改任何标签或属性。我为此使用HTMLParser。但我坚持写回档案。使用HTMLParser我可以解析并获取数据内容,我将在其中进行必要的更改。但如何把它放回我的html文件?python HTMLParser替换html文件中的一些字符串

请帮忙。这是我的代码:

class EntityHTML(HTMLParser.HTMLParser): 
    def __init__(self, filename): 
     HTMLParser.HTMLParser.__init__(self) 
     f = open(filename) 
     self.feed(f.read()) 

    def handle_starttag(self, tag, attrs): 
     """Needn't do anything here""" 
     pass 

    def handle_data(self, data): 
     print data 
     data = data.replace(",", "&sbquo") 
+1

请妥善缩进代码。 –

回答

2

HTMLParser不会在您的html文件的内存中构建任何表示。你可以自己做的handle_*()方法,但一个简单的方法是使用BeautifulSoup

>>> import re 
>>> from BeautifulSoup import BeautifulSoup 
>>> soup = BeautifulSoup('<a title=,>,</a>') 
>>> print soup 
<a title=",">,</a> 
>>> comma = re.compile(',') 
>>> for t in soup.findAll(text=comma): t.replaceWith(t.replace(',', '&sbquo')) 
>>> print soup 
<a title=",">&sbquo</a> 
+0

谢谢你。它工作完美。 – Divya

+0

但是,当我尝试将汤写入文件时,它给了我错误说:TypeError:预期字符缓冲区对象 – Divya

+0

f =打开(文件名,“rw”)f.write(汤) – Divya