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

求助:使用Pandas读取本地HTML表格时获取页面显示值而非隐藏代码

解决Pandas读取HTML时获取动态渲染时间值的问题

Pandas的read_html()只能解析静态HTML内容,而页面中显示的时间是通过JavaScript动态计算后渲染的,所以直接读取会拿到未执行的JS代码。以下是两种可行的解决方法:

方法1:用浏览器渲染引擎获取动态生成的HTML

使用Selenium或Playwright这类工具模拟浏览器加载页面,执行JS后再获取最终渲染的HTML,再用Pandas解析。

示例代码(Selenium)

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import pandas as pd

# 配置无头模式(不弹出浏览器窗口)
chrome_options = Options()
chrome_options.add_argument("--headless=new")

# 初始化Chrome浏览器
driver = webdriver.Chrome(options=chrome_options)

# 加载本地HTML文件,注意路径格式:file:/// + 本地绝对路径
local_file = "file:///C:/Users/xxx/Desktop/your_table.html"
driver.get(local_file)

# 等待JS执行完成(可根据页面情况调整等待时间)
driver.implicitly_wait(3)

# 获取渲染后的完整页面源码
rendered_html = driver.page_source

# 关闭浏览器
driver.quit()

# 用Pandas解析渲染后的HTML
dfs = pd.read_html(rendered_html)
# 取第一个表格(根据实际表格数量调整索引)
target_df = dfs[0]
print(target_df)

方法2:手动解析JS函数逻辑转换数值

如果不想依赖浏览器工具,可以先从HTML中提取JS函数的参数,再用Python实现Timefactor函数的转换逻辑,替换表格中的值。

示例代码

import re
import pandas as pd

# 读取本地HTML文件
with open("your_table.html", "r", encoding="utf-8") as f:
    raw_html = f.read()

# 正则匹配Timefactor函数的时间参数
time_pattern = r'Timefactor\("([^"]+)",\s*"raster"\)'

# 实现Timefactor的转换逻辑(需替换成实际函数的计算规则)
def convert_time(original_time):
    # 示例:假设原时间格式为"h:m:s",转换为"mm:ss.ms"并乘以对应系数
    h, m, s = map(float, original_time.split(":"))
    total_sec = h * 3600 + m * 60 + s
    # 此处系数需根据实际JS函数逻辑调整,示例仅作参考
    converted_sec = total_sec * 1.066
    mins = int(converted_sec // 60)
    secs = converted_sec % 60
    return f"{mins:02d}:{secs:.2f}"

# 读取原始表格
dfs = pd.read_html(raw_html)
target_df = dfs[0]

# 遍历目标列,替换JS代码为转换后的时间值
# 假设目标列是第2列(索引1),根据实际情况调整
target_col_idx = 1
for idx, cell in enumerate(target_df.iloc[:, target_col_idx]):
    cell_str = str(cell)
    if "Timefactor" in cell_str:
        match = re.search(time_pattern, cell_str)
        if match:
            original_time = match.group(1)
            target_df.iloc[idx, target_col_idx] = convert_time(original_time)

print(target_df)

两种方法对比

  • 浏览器渲染法:无需分析JS逻辑,通用性强,但需要安装浏览器驱动,运行速度稍慢。
  • 手动解析法:轻量快速,但需要准确还原JS函数的转换逻辑,适合JS逻辑简单的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:05:38