使用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 小时前
✨✨✨使用Python,OpenCV及图片拼接生成❤️LOVE❤️字样图,每张小图加随机颜色边框,大图加随机大小随机颜色边框
图像处理·python·opencv·numpy·图像拼接
Rsun045511 小时前
React相关面试题
前端·react.js·前端框架
MediaTea1 小时前
Python:collections.Counter 常用函数及应用
开发语言·python
如若1231 小时前
flash-attn 安装失败?从报错到成功的完整排雷指南(CUDA 12.8 + PyTorch 2.7)
人工智能·pytorch·python
007张三丰1 小时前
知乎高赞回答爬虫:从零开始,建立你的专属知识库
爬虫·python·知识库·python爬虫·知乎·高赞回答
鹏多多.1 小时前
Flutter使用screenshot进行截屏和截长图以及分享保存的全流程指南
android·前端·flutter·ios·前端框架
LawrenceLan2 小时前
37.Flutter 零基础入门(三十七):SnackBar 与提示信息 —— 页面反馈与用户交互必学
开发语言·前端·flutter·dart
李昊哲小课2 小时前
Python json模块完整教程
开发语言·python·json