使用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")
相关推荐
givemeacar21 小时前
十七:Spring Boot依赖 (2)-- spring-boot-starter-web 依赖详解
前端·spring boot·后端
辻戋1 天前
从零开始手写mini-webpack
前端·webpack·node.js
cch89181 天前
PHP vs 易语言:Web开发与桌面编程大对决
开发语言·前端·php
百撕可乐1 天前
NextJS官网实战02:项目的基础骨架搭建
前端·javascript·react.js
陈天伟教授1 天前
人工智能应用- 人工智能风险与伦理:01.数据安全
前端·人工智能·安全·xss·csrf
白小筠1 天前
Pytorch之张量的基本操作
人工智能·pytorch·python
用户69371750013841 天前
Android 17 完整更新详解:Beta 3 已达平台稳定,这些新功能值得期待
android·前端·android studio
self_correction1 天前
Python工具
网络·python·安全
Fevered 路小小呀!1 天前
mediapipe新版本怎么玩--面部特征检测
人工智能·python·计算机视觉
geyasi1 天前
【Flask】四、flask连接并操作数据库
数据库·python·flask