使用python脚本爬取前端页面上的表格导出为Excel

前几天有前端小伙伴说后端没写导出功能,但是现在人事需要用到这个表,要导出Excel给她,那就用脚本爬一下吧,30行代码搞定。


电脑需要有python3环境,用解释器打开,没包的下载包,然后跑一下就行,需要注意的是,直接用的find('table') ,如果有多个table,想要爬某个表格,那就指定id去查。下课。

python 复制代码
import requests
from bs4 import BeautifulSoup
import pandas as pd

#   获取网页内容
url = "http://127.0.0.1:53893/"
response = requests.get(url)
html_content = response.text

#  解析html 获取表格 提取表头
soup = BeautifulSoup(html_content, 'html.parser')
table = soup.find('table')

headers = []
for th in table.find_all('th'):
    headers.append(th.text.strip())

#  提取表格的行数据
rows = []
for tr in table.find_all('tr')[1:]:  # 从第二行开始,第一行是表头
    cells = tr.find_all('td')
    row = [cell.text.strip() for cell in cells]
    if row:
        rows.append(row)

df = pd.DataFrame(rows, columns=headers)

#  导出为Excel
df.to_excel('index.xlsx', index=False)

print("数据已成功导出到index.xlsx")
相关推荐
像是套了虚弱散1 小时前
DevEco Studio与Web联合开发:打造鸿蒙混合应用的全景指南
开发语言·前端·华为·harmonyos·鸿蒙
衬衫chenshan2 小时前
【CTF】强网杯2025 Web题目writeup
前端
飞翔的佩奇2 小时前
【完整源码+数据集+部署教程】【天线&水】舰船战舰检测与分类图像分割系统源码&数据集全套:改进yolo11-repvit
前端·python·yolo·计算机视觉·数据集·yolo11·舰船战舰检测与分类图像分割系统
哆啦A梦15883 小时前
点击Top切换数据
前端·javascript·vue.js
木头左3 小时前
最大回撤约束下ETF多因子动态止盈参数校准方案
python
汤姆yu3 小时前
2026版基于python的协同过滤音乐推荐系统
开发语言·python
程序猿追3 小时前
Vue组件化开发
前端·html
汤姆yu3 小时前
基于python的电子商务管理系统
开发语言·python
may_一一4 小时前
pycharm\python 安装下载
ide·python·pycharm
后台开发者Ethan4 小时前
FastAPI之 Python的类型提示
python·fastapi·ai编程