使用Python BeautifulSoup爬取表格后如何按打印格式整齐写入CSV?
实现逻辑与代码修正
现有代码核心问题
- 遍历每行时都用
w(覆盖写)模式打开文件,会清空之前写入的内容,最终文件仅会保留最后一行数据 - 写入内容未添加换行符
\n,所有内容会拼接在同一行,和控制台打印的分行效果不一致 - 文件打开操作放在行遍历循环内,频繁开关文件会额外损耗性能
实现逻辑说明
如果要输出和控制台打印完全一致的固定宽度对齐格式,按以下步骤执行即可:
- 提前打开文件,统一完成所有写入操作后再关闭,避免频繁开关和覆盖写入
- 先写入格式化后的表头,加换行符
- 逐行遍历表格数据,格式化后加换行符写入文件
- 如果需要标准逗号分隔的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
相关产品推荐
相关产品推荐

