如何将Python BeautifulSoup爬取的维基百科内容保存到文本文件
代码修复说明
核心问题
- 原代码中
print()函数仅负责控制台输出,无返回值,赋值给doc_text的变量实际为None,无法获取待写入的文本内容 - 原代码未添加文件操作逻辑,自然无法生成本地文本文件并写入内容
修复后可运行代码
import requests from bs4 import BeautifulSoup url_to_text = "https://en.wikipedia.org/wiki/Santiago" # 请求页面并处理编码避免乱码 response = requests.get(url_to_text) response.encoding = response.apparent_encoding soup = BeautifulSoup(response.content,'html.parser') # 收集所有符合要求的段落文本 content_list = [] for i in range(1, 50): current_p = soup("p")[i].text.strip() # 跳过空段落 if current_p: content_list.append(current_p) # 一次性写入本地文件,指定UTF-8编码避免乱码 with open("santiago_wiki_content.txt", "w", encoding="utf-8") as file: file.write("\n\n".join(content_list))
关键说明
- 使用
with open()语法操作文件,会自动完成文件关闭操作,避免资源泄露 - 必须指定
encoding="utf-8",否则Windows系统下写入非ASCII字符时会出现乱码 - 增加空段落过滤逻辑,避免生成的文件中存在大量无意义空白内容
内容的提问来源于stack exchange,提问作者raulfloresp
相关产品推荐
相关产品推荐

