2016-03-06 64 views
0

我想解析一些HTML,然后将该HTML写入.py文件。这里是我使用的代码:如何解析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

回答

0

在使用“写入”模式后,您似乎读取文件“Test.py”,这可能会导致数据丢失。

+0

是的!这似乎工作!谢谢! – HittmanA