我需要替换html页面的数据内容中的一些字符串。我不能直接使用替换功能,因为我只需要更改数据部分。它不应该修改任何标签或属性。我使用了HTMLParser
。但我坚持把它写回文件。使用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")
答案 0 :(得分: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>