Selenium 自动化点击动态加载表格中可点击 td 元素的完整解决方案

1次阅读

Selenium 自动化点击动态加载表格中可点击 td 元素的完整解决方案

本文详解如何在 selenium 中可靠点击伦敦证券交易所动态渲染页面中带 `.clickable.td-with-link` 类的 `

` 元素,涵盖 cookie 弹窗处理、动态内容等待、元素可见性与可点击性校验及多级页面跳转实践。

自动化抓取伦敦证券交易所(LSE)Price Explorer 页面(如 Bonds 分类页)时,直接调用 click() 失败是常见问题。根本原因并非代码逻辑错误,而是页面存在三层阻断机制:① 首次访问强制弹出 cookie 同意横幅;② 表格数据通过 angular 动态异步加载,

初始为空或含 class=”disabled” 占位符;③ 可点击

实际包裹在 内,直接对 调用 click() 常因事件委托失效或遮挡而失败。

以下为经过实测验证的稳健解决方案,采用显式等待 + 精准定位 + 安全交互策略:

✅ 步骤一:显式等待并接受 Cookie 弹窗

Cookie 横幅会阻塞后续所有元素交互。需先定位并点击「Accept All Cookies」按钮(XPath 稳定性较高,但建议配合 webdriverWait 防止过早查找):

from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options  options = Options() options.add_argument("--start-maximized") driver = webdriver.Chrome(options=options) wait = WebDriverWait(driver, 15)  # 延长超时至15秒,适应慢速网络  url = "https://www.php.cn/link/12b71d68d0493e7ac7c5e0558c0a498e" driver.get(url)  # 等待并点击 Cookie 接受按钮(关键前置步骤) try:     accept_btn = wait.until(         EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Accept All Cookies')]"))     )     accept_btn.click()     print("✅ Cookie banner accepted.") except Exception as e:     print("⚠️  Cookie banner not found or not clickable — proceeding anyway.")

注意:避免使用绝对 XPath(如 /html/body/div/div[2]/…),因其极易因页面结构微调而失效。优先选择含语义文本(如 “Accept All Cookies”)的相对 XPath 或 css 选择器

✅ 步骤二:等待动态表格真实数据加载完成

目标表格 #price-explorer-results-wrapper 加载后,其

内部仍可能处于 class=”disabled” 状态(即占位符)。需等待首个可点击的公司名称 出现且可见

# 等待表格主体(tbody)内出现至少一个有效的 instrument-name span first_company_span = wait.until(     EC.visibility_of_element_located((         By.CSS_SELECTOR,          "table#price-explorer-results-wrapper tbody tr.slide-panel td.instrument-name.gtm-trackable.td-with-link span.ellipsed"     )) ) print(f"✅ Found first company: {first_company_span.text.strip()}")

✅ 步骤三:安全点击公司名称并跳转详情页

直接对

调用 click() 易失败,应定位内部 并确保其可点击、无遮挡。推荐使用 ActionChains 模拟真实用户操作(滚动+点击),并捕获新窗口句柄:

from selenium.webdriver.common.action_chains import ActionChains  # 获取所有公司名称 span 元素(非 td!) company_spans = driver.find_elements(     By.CSS_SELECTOR,      "table#price-explorer-results-wrapper tbody tr.slide-panel td.instrument-name.gtm-trackable.td-with-link span.ellipsed" )  for i, span in enumerate(company_spans[:3]):  # 示例:仅处理前3家公司     try:         # 滚动到元素顶部,消除遮挡         driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", span)         wait.until(EC.element_to_be_clickable(span))          # 使用 ActionChains 点击(比 span.click() 更鲁棒)         ActionChains(driver).move_to_element(span).click().perform()          # 等待新窗口打开并切换         wait.until(lambda d: len(d.window_handles) > 1)         driver.switch_to.window(driver.window_handles[-1])          # 此处可开始解析公司详情页(如 https://www.londonstockexchange.com/stock/957X/3i-group-plc/company-page)         print(f"✅ Navigated to detail page for: {span.text.strip()}")          # 【示例】提取 Instrument ID(位于详情页右上角)         try:             instrument_id = wait.until(                 EC.presence_of_element_located((By.CSS_SELECTOR, "div.instrument-id span"))             ).text.strip()             print(f"   Instrument ID: {instrument_id}")         except:             print("   ❌ Could not extract Instrument ID")          # 关闭当前详情页,返回主窗口         driver.close()         driver.switch_to.window(driver.window_handles[0])      except Exception as e:         print(f"❌ Failed to click company #{i+1} ({span.text.strip()}): {str(e)}")         continue

⚠️ 关键注意事项总结

  • 绝不依赖 time.sleep():它不可靠且拖慢执行。全程使用 WebDriverWait 配合 expected_conditions(如 element_to_be_clickable, visibility_of_element_located)。
  • 定位目标要精准:.clickable.instrument-name… 是 的 class,但实际可点击区域是其子 。对 点击常因 Angular 事件绑定机制失败。

  • 处理动态禁用状态:若
    存在,说明数据尚未就绪,需等待其消失或被真实内容替换(可通过 EC.invisibility_of_element_located 显式等待)。

  • 管理多窗口:每次点击链接都会打开新标签页,务必及时 switch_to.window() 并 close(),避免句柄泄漏。
  • 反爬友好提示:添加 –disable-blink-features=AutomationControlled 和 user-agent 模拟真实浏览器(生产环境建议)。
  • 通过以上结构化流程,即可稳定实现从 LSE 动态表格中逐个点击公司名称、跳转详情页并提取结构化数据的全链路自动化。核心在于:尊重前端渲染生命周期,以用户视角设计交互,用显式等待替代猜测式延时。

text=ZqhQzanResources