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

如何用Python+BeautifulSoup提取JS生成表格中的隐藏Input文本

解决建议

1. 修复现有代码的逻辑错误

你的代码存在两个关键问题:

  • 循环中错误使用data.find('input'),data是当前行所有<td>的集合,应该用当前遍历的dat来查找input元素
  • 隐藏input的数据存储在value属性中,不是元素的文本内容,需要提取该属性值

修复后的代码如下:

import requests
from bs4 import BeautifulSoup

url = 'https://sigaf.transmuni.gob.ni/cgi-bin/tm_CPTechosMun.cgi?ejercicio=2022'
r = requests.get(url, verify=False)
soup = BeautifulSoup(r.text, 'html.parser')
table2022trans = soup.find('table', attrs={"id": "DESEMBOLSO"})

if table2022trans:
    # 直接查找所有tbody下的tr,简化遍历层级
    for muni in table2022trans.select('tbody tr'):
        # 遍历每个单元格
        for dat in muni.find_all('td'):
            input_elem = dat.find('input')
            if input_elem:
                # 提取input的value属性值
                input_value = input_elem.get('value')
                if input_value:  # 过滤空值
                    print(input_value)

2. 处理JavaScript渲染的问题

如果上述代码仍无法获取数据,说明表格是浏览器执行JavaScript后动态生成的,requests无法执行JS,这时需要使用支持页面渲染的工具,比如Selenium:

步骤:

  • 安装Selenium:pip install selenium
  • 下载对应浏览器的驱动(如ChromeDriver)并配置到环境变量

示例代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time

# 配置无头模式,不显示浏览器窗口
options = Options()
options.add_argument('--headless=new')

driver = webdriver.Chrome(options=options)
driver.get('https://sigaf.transmuni.gob.ni/cgi-bin/tm_TechosMunRT01.cgi?ejercicio=2022&invok=pub')

# 等待页面渲染完成
time.sleep(3)

table = driver.find_element(By.ID, 'DESEMBOLSO')
# 遍历所有行
for row in table.find_elements(By.TAG_NAME, 'tr'):
    # 遍历每个单元格
    for cell in row.find_elements(By.TAG_NAME, 'td'):
        input_elem = cell.find_element(By.TAG_NAME, 'input')
        if input_elem:
            print(input_elem.get_attribute('value'))

driver.quit()

额外提示

  • 可再次检查网页的网络请求,确认是否有AJAX接口加载数据(虽然你判断不是API生成,但多一层验证能更高效解决问题),若存在直接调用接口会比渲染页面更高效
  • 注意网站的爬取规则,控制请求频率,避免给服务器造成不必要的压力

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:57:40