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

如何将DataFrame导出到Excel文件?解决数组形状广播报错

问题描述

将DataFrame导出至Excel文件时,程序持续抛出错误:
could not broadcast input array from shape (50,56) into shape (50,)
不清楚应当如何调整数组形状以修复该问题,原实现代码如下:

from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd

URL = "https://www.nba.com/stats/players/traditional/?sort=PTS&dir=-1&Season=2021-22&SeasonType=Playoffs"

driver = webdriver.Chrome()

driver.maximize_window()
driver.get(URL)

soup = BeautifulSoup(driver.page_source, 'lxml')
tables = soup.find_all('table')

response_data = pd.read_html(str(tables))


driver.implicitly_wait(5)
driver.quit()


new_storage = pd.DataFrame(response_data)
writer = pd.ExcelWriter('2021 Data.xlsx')
new_storage.to_excel(writer, '2021')

writer.save()

read_file = pd.read_excel ("2021 Data.xlsx")
错误原因
  • pd.read_html()的返回值是DataFrame对象组成的列表,不是单个DataFrame。当前页面解析到的目标球员数据表形状为(50,56),直接把存放这个DataFrame的列表传入pd.DataFrame()构造函数,相当于尝试把二维表格数据塞进一维列表结构,维度不匹配触发numpy广播报错。
  • 隐式等待driver.implicitly_wait(5)的调用位置错误,放在页面源码解析完成、即将退出浏览器的位置完全不会生效,很容易出现动态表格还没加载完就抓取源码,拿到空数据的问题。
修复方案

调整等待位置,直接取出read_html返回列表里的目标表格,不需要额外套一层DataFrame构造,推荐用上下文管理器处理Excel写入操作,修复后代码如下:

from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd

URL = "https://www.nba.com/stats/players/traditional/?sort=PTS&dir=-1&Season=2021-22&SeasonType=Playoffs"

driver = webdriver.Chrome()
# 提前设置隐式等待,在页面加载阶段生效
driver.implicitly_wait(5)
driver.maximize_window()
driver.get(URL)

soup = BeautifulSoup(driver.page_source, 'lxml')
tables = soup.find_all('table')
# read_html返回DataFrame列表,取第一个元素就是目标球员表
response_data = pd.read_html(str(tables))[0]
driver.quit()

# 用上下文管理器写Excel,自动处理资源释放和保存
with pd.ExcelWriter('2021 Data.xlsx') as writer:
    response_data.to_excel(writer, sheet_name='2021')

read_file = pd.read_excel("2021 Data.xlsx")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 11:01:23