You need to enable JavaScript to run this app. 使用Python BeautifulSoup爬取表格后如何按打印格式整齐写入CSV?
优惠活动
大模型
产品
解决方案
定价
更多

使用Python BeautifulSoup爬取表格后如何按打印格式整齐写入CSV?

实现逻辑与代码修正

现有代码核心问题

  • 遍历每行时都用w(覆盖写)模式打开文件,会清空之前写入的内容,最终文件仅会保留最后一行数据
  • 写入内容未添加换行符\n,所有内容会拼接在同一行,和控制台打印的分行效果不一致
  • 文件打开操作放在行遍历循环内,频繁开关文件会额外损耗性能

实现逻辑说明

如果要输出和控制台打印完全一致的固定宽度对齐格式,按以下步骤执行即可:

  1. 提前打开文件,统一完成所有写入操作后再关闭,避免频繁开关和覆盖写入
  2. 先写入格式化后的表头,加换行符
  3. 逐行遍历表格数据,格式化后加换行符写入文件
  4. 如果需要标准逗号分隔的CSV文件,可以直接用Python内置的csv模块写入,无需手动处理对齐

修正后代码(和打印格式完全一致)

from bs4 import BeautifulSoup
import requests
import time

htmlText = requests.get('https://www.fangraphs.com/teams/mariners/stats').text
soup = BeautifulSoup(htmlText, 'lxml')
playerTable = soup.find('div', class_='team-stats-table')

def BattingStats():
    headers = [th.text for th in playerTable.find_all("th")]
    fmt_string = " ".join(["{:<25}", *["{:<6}"] * (len(headers) - 1)])
    # 打开文件放在循环外,用w模式一次写入所有内容
    with open('MarinersBattingStats.csv', 'w', encoding='utf-8') as f:
        # 先写表头,加换行符
        header_line = fmt_string.format(*headers)
        f.write(header_line + '\n')
        print(header_line)
        # 遍历行写入数据
        for tr in playerTable.find_all("tr")[1:55]:
            tds = [td.text for td in tr.select("td")]
            line = fmt_string.format(*tds)
            f.write(line + '\n')
            print(line)

if __name__ == '__main__':
    # 定时爬取逻辑可按需开启,测试时直接调用即可
    # while True:
    #     BattingStats()
    #     timeWait = 100
    #     time.sleep(432 * timeWait)
    BattingStats()

标准CSV格式写入示例(可选)

如果需要符合通用规范的CSV文件(方便用Excel等工具打开),可以用内置csv模块实现,代码如下:

import csv
# 其他引入和页面解析代码保持不变
def BattingStatsCsv():
    headers = [th.text for th in playerTable.find_all("th")]
    with open('MarinersBattingStats_standard.csv', 'w', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        for tr in playerTable.find_all("tr")[1:55]:
            tds = [td.text for td in tr.select("td")]
            writer.writerow(tds)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 20:51:03