Python网页爬虫写入CSV文件空白无数据问题排查
问题根因
你的CSV文件完全空白是代码运行中途抛出未捕获异常、程序提前终止导致的,具体错误点如下:
- 分页请求的URL拼接错误:你直接把HTML源码里的转义字符
&写进了请求地址,Python发请求时参数分隔符必须用原生&,否则服务端无法识别per_page参数,返回的页面结构和预期不符。 - 元素定位语法错误:
row.find('td', {'gf'})、row.find('td', {'ga'})、胜率字段的find写法,都是在匹配自带对应名称自定义属性的td标签,但实际页面里这些列的td是class属性为对应值,这些代码会返回None,后续调用.text时直接触发AttributeError中断程序。 - 文件写入参数缺失:打开CSV文件时没有指定编码和
newline参数,Windows环境下默认用GBK编码写入,遇到特殊字符容易触发编码错误;且程序异常退出时不会自动刷新文件缓冲区,最终连表头都不会写入文件,呈现完全空白的状态。 - 额外细节问题:直接取
.text拿到的字段前后带有大量换行、空格冗余,会导致CSV里的内容存在多余空白。
修复后可运行代码
import requests from bs4 import BeautifulSoup import csv import lxml html_page = requests.get('https://www.scrapethissite.com/pages/forms/?page_num=1').text soup = BeautifulSoup(html_page, 'lxml') # 获取总页数 pagenum = soup.find('ul', {'class': 'pagination'}) n = pagenum.findAll('li')[-2].find('a')['href'].split('=')[1] page = range(1, int(n) + 1) # 写入文件时指定utf-8编码,加newline=''避免csv生成多余空行 with open('HockeyLeague.csv', 'w', encoding='utf-8', newline='') as f: csv_writer = csv.writer(f) csv_writer.writerow(['team_name', 'year', 'wins', 'losses', 'win_perc', 'goal_for', 'goal_against']) for p in page: # 修正URL里的&为原生& html_page = requests.get(f'https://www.scrapethissite.com/pages/forms/?page_num={p}&per_page=25').text soup = BeautifulSoup(html_page, 'lxml') table = soup.find('table', {'class': 'table'}) for row in table.findAll('tr', {'class': 'team'}): # 修正元素定位逻辑,所有字段取text后加strip()清理空白 team_name = row.find('td', {'class': 'name'}).text.strip() year = row.find('td', {'class': 'year'}).text.strip() wins = row.find('td', {'class': 'wins'}).text.strip() losses = row.find('td', {'class': 'losses'}).text.strip() goal_for = row.find('td', {'class': 'gf'}).text.strip() goal_against = row.find('td', {'class': 'ga'}).text.strip() try: win_perc = row.find('td', {'class': 'pct text-success'}).text.strip() except: win_perc = row.find('td', {'class': 'pct text-danger'}).text.strip() csv_writer.writerow([team_name, year, wins, losses, win_perc, goal_for, goal_against])
补充说明
运行修复后的代码会自动在同目录生成正常写入数据的HockeyLeague.csv文件,如果后续爬取其他站点遇到类似写入空白的问题,可以优先检查是否存在未捕获的异常中断了写入流程,以及文件打开参数是否符合当前系统环境要求。
内容的提问来源于stack exchange,提问作者Ele
相关产品推荐
相关产品推荐

