使用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 分钟前
python中的class类
开发语言·python
idwangzhen12 分钟前
GEO优化系统哪家更专业
python·信息可视化
iRuriCatt18 分钟前
智慧景区管理系统 | 计算机毕设项目
java·前端·spring boot·vue·毕设
diediedei29 分钟前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
m0_5613596731 分钟前
使用Python自动收发邮件
jvm·数据库·python
程序员清洒41 分钟前
Flutter for OpenHarmony:Icon 与 IconButton — 图标系统集成
前端·学习·flutter·华为
naruto_lnq1 小时前
用Python批量处理Excel和CSV文件
jvm·数据库·python
b2077211 小时前
Flutter for OpenHarmony 身体健康状况记录App实战 - 提醒设置实现
python·flutter·macos·cocoa·harmonyos
2301_822365031 小时前
数据分析与科学计算
jvm·数据库·python
河北小博博1 小时前
分布式系统稳定性基石:熔断与限流的深度解析(附Python实战)
java·开发语言·python