2013-04-26 104 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建議

相關問題