使用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")
相关推荐
掘金酱2 分钟前
「寻找年味」 沸点活动|获奖名单公示🎊
前端·人工智能·后端
患得患失94912 分钟前
【前端】前端动画优化的核心
前端
Xin_z_14 分钟前
Vue3 + Sticky 锚点跳转被遮挡问题解决方案
前端·javascript·vue.js
多恩Stone14 分钟前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
REDcker20 分钟前
WebCodecs VideoDecoder 的 hardwareAcceleration 使用
前端·音视频·实时音视频·直播·webcodecs·videodecoder
修炼前端秘籍的小帅23 分钟前
Stitch——Google热门的免费AI UI设计工具
前端·人工智能·ui
精神状态良好29 分钟前
实战:从零构建本地 Code Review 插件
前端·llm
荒诞英雄30 分钟前
Vue3 Teleport我真是没招了
前端·vue.js
QQ40220549631 分钟前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再31 分钟前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip