打开所有子文件夹内的html文件源代码,并将源代码转换成utf-8格式的字符
时间: 2024-04-15 08:30:32 浏览: 93
你可以使用Python的BeautifulSoup库和编码转换功能来实现这个任务。以下是修改后的示例代码:
```python
import os
from bs4 import BeautifulSoup
folder_path = 'C:/Users/test/Desktop/DIDItest'
html_files = []
# 遍历文件夹下所有子文件夹内的HTML文件
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.html'):
html_files.append(os.path.join(root, file))
# 打开HTML文件并将源代码转换为utf-8格式的字符串
for file_path in html_files:
with open(file_path, 'r', encoding='utf-8') as file:
html_code = file.read()
soup = BeautifulSoup(html_code, 'html.parser')
source_code = soup.get_text()
# 将源代码转换为utf-8格式的字符串
source_code_utf8 = source_code.encode('utf-8')
# 在这里可以对源代码字符串进行进一步处理或保存到文件中
```
以上代码会遍历指定文件夹及其子文件夹下的所有HTML文件,并将每个文件的源代码提取出来。然后,通过调用`.encode('utf-8')`将源代码转换为utf-8格式的字符串。
你可以在代码中的注释部分进行进一步的处理或保存操作。
阅读全文
相关推荐


















