如何解析HTML然后写入.py文件

How to parse HTML and then write it to a .py file

我正在尝试解析一些 HTML,然后将 HTML 写入 .py 文件。这是我正在使用的代码:

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        print(data)
        f = open('/Users/austinhitt/Desktop/Test.py', 'w')
        f = open('/Users/austinhitt/Desktop/Test.py', 'r')
        t = f.read()
        f = open('/Users/austinhitt/Desktop/Test.py', 'w')
        f.write(t + '\n' + data)
        f.close()

parser = MyHTMLParser()
parser.feed('<html>'
            '<body>'
            '<p>import time as t</p>'
            '<p>from os import path</p>'
            '<p>import os</p>'
            '</body>'
            '</html>')

我没有收到任何错误,但是只有最后一个 p 标记的内容被放入文件中。我只想将 p 标签内的内容添加到文件中,而不是 p 标签本身。我需要将每个 p 标签的内容添加到文件中,并且我不想使用 BeautifulSoup 或其他非内置模块。我正在使用 Python 3.5.1

好像是在使用"write"模式后读取文件"Test.py",可能会导致数据丢失。