我需要替换 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")
最佳答案
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>
关于python HTMLParser 替换html文件数据中的一些字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7339042/