从.html文件中提取文本,删除HTML,并使用Python和Beautiful Soup写入文本文件

时间:2013-04-26 16:46:25

标签: python beautifulsoup

我正在使用Beautiful Soup 4从HTML文件中提取文本,并使用get_text()我可以轻松地只提取文本,但现在我正在尝试将该文本写入纯文本文件,以及何时我知道,我收到的消息是“416”。这是我正在使用的代码:

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

控制台的输出是416,但没有任何内容写入文本文件。我哪里出错?

1 个答案:

答案 0 :(得分: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()

以更加pythonic的风格

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建议的那样