python - CSV writer - 在脚本运行时写入 csv 但不保存
问题描述
我的代码似乎正在工作并将数据保存到 csv 但脚本结束后,没有数据。当脚本运行时,我的 csv 文件存储数据,如果我中断它,我可以看到一些数据。
import requests
from bs4 import BeautifulSoup
import csv
def main():
page = 1
page_has_data = True
while page_has_data:
r = requests.get("http://scrapethissite.com/pages/forms/", params=dict(per_page=100, page_num=page))
soup = BeautifulSoup(r.text, features="lxml")
print("----- Scraping page number", page)
page += 1
teams = soup.findAll("tr", "team")
if len(teams) == 0:
page_has_data = False
with open("hockey_stats.csv", "w", newline="") as results:
writer = csv.writer(results)
for team in teams:
team_name = team.find("td", "name").get_text(strip=True)
team_year = team.find("td", "year").get_text(strip=True)
team_win = team.find("td", "wins").get_text(strip=True)
team_loss = team.find("td", "losses").get_text(strip=True)
team_pct_win = team.find("td", "pct text-success")
team_goalsfor = team.find("td", "gf").get_text(strip=True)
team_goalsagainst = team.find("td", "ga").get_text(strip=True)
team_plus_minus = team.find("td", "diff text-success")
writer.writerow([team_name, team_year,team_win, team_loss, team_pct_win, team_goalsfor, team_goalsagainst, team_plus_minus])
results.close()
解决方案
我认为您的代码段有两个问题。您正在以写入模式打开文件。而是打开它附加模式(“a”)。当您使用新请求进行迭代时,您最终会覆盖您上次写入文件的数据(如果文件以写入模式打开 - “w”)。最后一个请求将没有任何数据,并且您用空数据覆盖您的文件。
其次,你不需要'results.close()'。with 语句将负责关闭文件。
推荐阅读
- angular - 调试两个独立的应用程序,Angular 和 Web API
- django-viewflow - Django-viewflow 如何获取当前用户?
- jmeter - Jmeter - 登录 - cookie 问题
- javascript - jsPDF显示打印页面而不是下载文件
- python - 按百分比随机划分和存储 SQL 表
- ios - Swift 日期生成问题
- python - 我使用哪个小部件的 after 方法是否重要?
- r - 通过使用 group_split 和 group_map 对变量进行分组,使用 tabyl 制表
- ansible - 使用 pip 命令时出现 ansible 抛出错误
- python - ValueError:长度不正确的密文