You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中BeautifulSoup解析内容写入txt时截断更新异常求助

解决思路

核心是不要在循环内重复打开文件,先把所有解析好的内容收集起来,再一次性用写入模式("w")覆盖文件——"w"模式会自动截断原有内容,不需要手动调用truncate(0)。

修改后的代码
import requests
from bs4 import BeautifulSoup

url = "https://rocket-league.com/trade/465ec00f-2f5c-48e2-831e-2e294683ad56"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

# 先收集所有要写入的内容
output_lines = []
for e in soup.select('.rlg-trade__itemshas .--hover'):
    items = ' '.join(list(e.stripped_strings)[:-2])
    output_lines.append(f"[H] {items}\n")

# 一次性写入文件,"w"模式自动清空原有内容
with open("hs.txt", "w") as h:
    h.writelines(output_lines)
问题原因说明
  • 原代码用"a"(追加模式)循环写入:每次打开文件都会在原有内容末尾追加,第二次运行时自然会出现重复内容。
  • 尝试在循环内用truncate(0):每次打开文件都会先清空,然后写入当前循环的单条内容,最终只会保留最后一条数据。

内容的提问来源于stack exchange,提问作者yusuf kuşçu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:30:52