从.html文件中提取文本,删除HTML,并使用Python和美丽的汤写入文本文件
问题描述:
我使用美丽的汤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
,但没有被写入到文本文件中。我哪里错了?
答
您需要将文本发送到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建议
需要关闭该文件 – bernie 2013-04-26 16:51:42
或者您可以使用,在2.5+的'with'声明有处理你 – bernie 2013-04-26 16:52:09
你试过检查'汤'和'soup.get_text()'? – 2013-04-26 17:04:58