python实现批量转换html文件为txt文件
时间: 2023-12-17 11:03:14 浏览: 34
可以使用Python中的BeautifulSoup库来实现将HTML文件转换为纯文本的操作。以下是一个基本的示例代码:
```python
from bs4 import BeautifulSoup
import os
# 遍历指定目录下的所有html文件
def convert_html_to_txt(directory):
for filename in os.listdir(directory):
if filename.endswith(".html"):
html_file = os.path.join(directory, filename)
with open(html_file, "r", encoding="utf-8") as f:
# 读取html文件内容
html_content = f.read()
# 使用BeautifulSoup解析html
soup = BeautifulSoup(html_content, 'html.parser')
# 获取纯文本内容
txt_content = soup.get_text()
# 将纯文本内容保存到txt文件中
txt_file = os.path.splitext(html_file)[0] + ".txt"
with open(txt_file, "w", encoding="utf-8") as txt:
txt.write(txt_content)
# 指定目录
directory = "path/to/html/files"
# 调用函数
convert_html_to_txt(directory)
```
在上面的示例代码中,我们首先遍历指定目录下的所有HTML文件,然后读取HTML文件内容并使用BeautifulSoup解析HTML,最后获取纯文本内容并将其保存到TXT文件中。需要注意的是,在使用BeautifulSoup解析HTML时,我们可以指定不同的解析器,例如`html.parser`、`lxml`等。