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

Python:BeautifulSoup爬取数据写入文本文件仅一行的解决方法

解决文件仅写入一行的问题

问题原因

你使用'w'模式在循环内重复打开文件时,每次都会清空文件原有内容并写入当前行数据,导致最终文件只保留了循环的最后一行结果。

两种修复方案

方案1:循环外打开文件,逐行写入

将文件打开操作移到循环外部,用'w'模式初始化文件,循环内逐行写入(记得添加换行符\n避免内容挤在一行):

from bs4 import BeautifulSoup
import requests

page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month")

soup = BeautifulSoup(page.content,'html.parser')

# 定位数据表格与行
table = soup.find(class_="tinytable")
rows = table.find_all('tr')

# 循环外打开文件,一次性完成写入操作
with open('TopInsiderMonth.txt', 'w') as f:
    for row in rows:
        data = row.find_all("td")
        # 提取各字段数据,做索引越界兼容
        ticker = data[3].get_text() if len(data) > 3 else "Ticker representing the company"
        company = data[4].get_text() if len(data) > 4 else "Name"
        insider = data[6].get_text() if len(data) > 6 else "Position of trader"
        trade_type = data[7].get_text() if len(data) > 7 else "Buy or sell"
        value = data[12].get_text() if len(data) > 12 else "Monetary value"
        
        # 构造行内容并添加换行符
        line_content = f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}\n'
        print(line_content.strip())
        f.write(line_content)

方案2:先收集所有内容,一次性写入

先把所有要写入的内容收集到列表中,最后一次性写入文件,减少IO操作次数,效率更高:

from bs4 import BeautifulSoup
import requests

page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month")

soup = BeautifulSoup(page.content,'html.parser')

table = soup.find(class_="tinytable")
rows = table.find_all('tr')

# 初始化列表存储所有行内容
output_content = []
for row in rows:
    data = row.find_all("td")
    ticker = data[3].get_text() if len(data) > 3 else "Ticker representing the company"
    company = data[4].get_text() if len(data) > 4 else "Name"
    insider = data[6].get_text() if len(data) > 6 else "Position of trader"
    trade_type = data[7].get_text() if len(data) > 7 else "Buy or sell"
    value = data[12].get_text() if len(data) > 12 else "Monetary value"
    
    line_content = f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}'
    print(line_content)
    output_content.append(line_content)

# 一次性写入所有内容,每行用换行符分隔
with open('TopInsiderMonth.txt', 'w') as f:
    f.write('\n'.join(output_content))

关键知识点

  • 'w'模式:打开文件时会清空原有内容,适合初始化文件或一次性写入;
  • 'a'模式:打开文件时会保留原有内容,新内容追加到末尾,适合多次写入场景;
  • 写入文本时必须添加\n换行符,否则所有内容会合并为一行。

内容的提问来源于stack exchange,提问作者Gamer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:20:26