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

如何用Selenium抓取表格中隐藏的tr属性与td值?

解决Selenium抓取隐藏/源码可见元素数据的方法

核心思路

Selenium默认仅返回可见元素的文本,但可以通过直接读取元素属性、执行JavaScript操作DOM这两种方式,获取仅在源码中可见的目标数据。

具体实现方案

1. 提取data-*类自定义属性

对于data-league、data-home这类内嵌在元素标签里的属性,直接用get_attribute()方法读取,不受元素可见性影响:

# 先定位表格所有行
rows = driver.find_elements(By.TAG_NAME, "tr")
for row in rows:
    # 逐个读取data属性
    league = row.get_attribute("data-league")
    home_team = row.get_attribute("data-home")
    away_team = row.get_attribute("data-away")
    match_time = row.get_attribute("data-time")
    match_date = row.get_attribute("data-date")

2. 抓取certainty、odds及百分比概率

如果这些数据存在于隐藏<td>或JS渲染的元素中:

  • 方式一:通过元素定位+textContent获取文本(支持隐藏元素)
# 假设certainty对应class为"certainty"的td
certainty = row.find_element(By.CLASS_NAME, "certainty").get_attribute("textContent").strip()
# 同理提取odds和百分比概率
odds = row.find_element(By.CLASS_NAME, "odds").get_attribute("textContent").strip()
probability = row.find_element(By.CLASS_NAME, "probability").get_attribute("textContent").strip()
  • 方式二:执行JavaScript直接提取DOM数据
# 传入当前行元素,用JS提取目标内容
extract_script = """
const row = arguments[0];
return {
    certainty: row.querySelector('.certainty').textContent.trim(),
    odds: row.querySelector('.odds').textContent.trim(),
    probability: row.querySelector('.probability').textContent.trim()
};
"""
row_data = driver.execute_script(extract_script, row)
certainty = row_data['certainty']
odds = row_data['odds']
probability = row_data['probability']

3. 处理动态加载的隐藏内容

如果数据是页面加载后通过AJAX/JS动态插入的,需要先等待元素加载完成:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待所有表格行加载到DOM中
wait = WebDriverWait(driver, 10)
rows = wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, "tr")))

4. 极端情况:数据仅在原始源码未渲染

如果目标数据完全未被渲染到DOM中,可直接获取页面源码后用解析库提取:

from bs4 import BeautifulSoup

# 获取当前页面源码
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')
# 解析表格行提取数据
for row in soup.find_all('tr'):
    league = row.get('data-league')
    # 其他属性同理提取

关键注意点

  • 避免使用元素的text属性,它仅返回可见文本;优先用textContent或innerHTML获取完整内容
  • 定位元素时,尽量使用精准的选择器(如ID、唯一class、XPath),避免因页面结构变化导致定位失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:25:57