python HTMLParser替换html文件数据中的一些字符串

时间:2011-09-07 18:54:40

标签: python html-parsing

我需要替换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")

1 个答案:

答案 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>