You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取investing.com爬取表格th标签的data-col-name作为列名

你需要遍历所有th标签,提取其data-col-name自定义属性作为表头,BeautifulSoup的标签对象可直接通过get()方法安全获取属性值,修改后的代码如下:

import pandas as pd
from bs4 import BeautifulSoup

# 假设你之前已经完成了页面请求和soup初始化操作
table_rows = soup.find("tbody").find_all("tr")

table = []
for i in table_rows:
    td = i.find_all("td")
    row = [cell.string for cell in td]
    table.append(row)
    
columns = soup.find("thead").find_all("th")
# 提取所有th的data-col-name属性作为列名
column_names = [th.get("data-col-name") for th in columns]

df_temp = pd.DataFrame(data=table, columns=column_names)
# 原append方法已被pandas弃用,推荐使用concat方法合并
df_dji = pd.concat([df_dji, df_temp], ignore_index=True)

补充说明:

  • 如果部分th不存在data-col-name属性,get()方法会返回None,你可以根据需要给默认值,比如th.get("data-col-name", f"未知列{index}"),配合enumerate遍历即可。
  • 注意保证表头的数量和表格每行的td数量一致,否则创建DataFrame时会报错。

内容的提问来源于stack exchange,提问作者CpF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 14:45:00