2013-04-26 103 views
1

我使用美丽的汤4从HTML文件中提取文本,并使用get_text()我可以轻松地提取文本,但现在我试图将该文本写入纯文本文件,当我这样做时,我收到消息“416”。下面是我使用的代码:从.html文件中提取文本,删除HTML,并使用Python和美丽的汤写入文本文件

from bs4 import BeautifulSoup 
markup = open("example1.html") 
soup = BeautifulSoup(markup) 
f = open("example.txt", "w") 
f.write(soup.get_text()) 

和输出到控制台是416,但没有被写入到文本文件中。我哪里错了?

+1

需要关闭该文件 – bernie 2013-04-26 16:51:42

+0

或者您可以使用,在2.5+的'with'声明有处理你 – bernie 2013-04-26 16:52:09

+0

你试过检查'汤'和'soup.get_text()'? – 2013-04-26 17:04:58

回答

4

您需要将文本发送到BeautifulSoup类。也许尝试markup.read()

from bs4 import BeautifulSoup 
markup = open("example1.html") 
soup = BeautifulSoup(markup.read()) 
markup.close() 
f = open("example.txt", "w") 
f.write(soup.get_text()) 
f.close() 

,并在更Python风格

from bs4 import BeautifulSoup 

with open("example1.html") as markup: 
    soup = BeautifulSoup(markup.read()) 

with open("example.txt", "w") as f: 
    f.write(soup.get_text()) 

为@bernie建议

相关问题