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

Beautiful Soup仅获取表格表头求助:网页表格数据无法导出至CSV

解决动态渲染表格的爬取问题

问题原因

这个页面的表格是JavaScript动态加载的,requests直接获取的静态HTML仅包含表格框架,实际数据是页面加载完成后通过JS从后端接口拉取并渲染的,所以你的BeautifulSoup代码只能抓到空结构。

解决方案1:使用Selenium模拟浏览器渲染

通过模拟浏览器加载页面,等待JS执行完成后再抓取完整的HTML内容:

  1. 先安装依赖:
pip install selenium
  1. 下载对应浏览器的驱动(比如ChromeDriver),确保驱动路径能被Python找到。

  2. 完整代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import csv

# 初始化Chrome浏览器(需提前配置ChromeDriver)
driver = webdriver.Chrome()
driver.get('http://www.ameren.com/illinois/residential/supply-choice/renewables/interconnection-queue')

# 等待表格加载完成,超时时间10秒
try:
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.TAG_NAME, "table"))
    )
    # 获取渲染后的完整页面源码
    page_source = driver.page_source
    soup = BeautifulSoup(page_source, 'html5lib')
    table = soup.find("table")
    
    # 提取所有行数据(包含表头)
    table_data = []
    for row in table.find_all('tr'):
        # 同时提取th(表头)和td(单元格)的文本,去除多余空格
        cells = [cell.get_text(strip=True) for cell in row.find_all(['th', 'td'])]
        if cells:  # 过滤空行
            table_data.append(cells)
    
    # 打印数据
    print(table_data)
    
    # 保存到CSV文件
    with open('interconnection_queue.csv', 'w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerows(table_data)
        
finally:
    # 关闭浏览器
    driver.quit()

解决方案2:直接请求后端API(更高效)

打开浏览器开发者工具(F12),切换到Network标签,刷新页面后找XHR/fetch类型的请求,通常能找到加载表格数据的JSON接口。直接请求这个接口可以跳过浏览器渲染,效率更高:

示例代码(需替换为实际找到的API地址):

import requests
import csv

# 替换为你在开发者工具中找到的真实API接口URL
api_url = "http://www.ameren.com/api/path/to/interconnection-queue-data"
response = requests.get(api_url)
response.raise_for_status()  # 检查请求是否成功
data = response.json()

# 提取表头和数据行
if data:
    headers = list(data[0].keys())
    rows = [headers] + [list(item.values()) for item in data]
    
    # 保存到CSV
    with open('interconnection_queue.csv', 'w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerows(rows)
else:
    print("未获取到数据")

验证方法

运行代码后,检查生成的interconnection_queue.csv文件,应该包含完整的表格数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:22:54