Python BeautifulSoup提取表格数据:HTML表格转CSV示例
讲解用BeautifulSoup解析HTML table标签,遍历tr和td把表格数据读成二维列表,再导出成CSV文件,适合抓取网页上的名单、价格、排行榜。
场景痛点
网页上有一张产品价格表、比赛成绩单、人员名单,手动复制粘贴到Excel里,表头对齐一塌糊涂,合并单元格还要重新拆。用BeautifulSoup定位到table标签,按行按列遍历,自动导出成CSV,Excel直接打开就是整齐的表格。
用到的库
pip install requests beautifulsoup4 lxml
完整代码
# 导入库
import csv
import requests
from bs4 import BeautifulSoup
def extract_table(url, table_index=0):
"""从网页提取第table_index张表格,返回二维列表"""
headers = {
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 Chrome/124.0.0.0 Safari/537.36"),
}
resp = requests.get(url, headers=headers, timeout=10)
resp.encoding = resp.apparent_encoding
soup = BeautifulSoup(resp.text, "lxml")
# 找到所有表格
tables = soup.find_all("table")
print(f"页面共 {len(tables)} 张表格")
if not tables:
return []
table = tables[table_index]
rows = []
# tr是行,th是表头单元格,td是普通单元格
for tr in table.find_all("tr"):
cells = []
# 同时处理th和td
for cell in tr.find_all(["th", "td"]):
# get_text拿到单元格文字,strip去掉空白
cells.append(cell.get_text(strip=True))
if cells: # 跳过空行
rows.append(cells)
return rows
def save_to_csv(rows, filename="table.csv"):
"""把二维列表存成CSV,带BOM方便Excel打开中文不乱码"""
with open(filename, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerows(rows)
print(f"已保存 {len(rows)} 行到 {filename}")
def main():
# 用一个包含示例表格的公开页面
url = "https://example.com"
try:
rows = extract_table(url, table_index=0)
if rows:
print("前3行预览:")
for r in rows[:3]:
print(r)
save_to_csv(rows, "table.csv")
else:
print("页面没有表格")
except Exception as e:
print("出错:", e)
if __name__ == "__main__":
main()
代码讲解
soup.find_all("table")找到页面里所有表格,一个网页可能有多张,用table_index指定取第几张。- 外层循环
find_all("tr")遍历每一行,内层循环find_all(["th", "td"])遍历行里的每个单元格,表头和数据单元格统一处理。 cell.get_text(strip=True)取单元格文字,自动去掉前后空格和换行。csv.writer把二维列表直接写成CSV,encoding="utf-8-sig"带BOM,Excel双击打开中文不会乱码。newline=""是Python写CSV的标准做法,避免Windows上多出空行。
运行结果
运行后控制台打印页面有几张表、前3行预览,当前目录生成 table.csv 文件,用Excel打开就是一行行整齐的数据。如果目标页面没有表格,会提示"页面没有表格"。
注意事项
- 复杂表格有合并单元格(rowspan、colspan),简单遍历会错位,需要根据实际情况补全。
- 有些网站用div模拟表格而不是真table标签,这时要按CSS选择器定位。
- 表格里可能嵌套了链接、图片,
get_text只拿得到文字,拿不到链接地址;要链接就额外找a["href"]。 - CSV文件用Excel打开如果还是乱码,确认保存时用的是
utf-8-sig而不是utf-8。

更新时间:2026-09-14 20:51:07
上一篇:Python BeautifulSoup解析网页提取文字:标签选择与清洗