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

如何用Selenium和Python抓取带行内下拉按钮的表格数据?

解决Selenium抓取带行内下拉按钮的表格数据问题

以下是针对该场景的具体实现方案:

核心实现逻辑

  • 定位目标表格并遍历所有数据行
  • 对每行定位下拉按钮并触发点击操作
  • 等待展开内容加载完成后,提取该行完整数据
  • 处理元素过期、不可点击等常见异常

代码示例

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.common.exceptions import StaleElementReferenceException

# 初始化浏览器实例
driver = webdriver.Chrome()
driver.get("你的目标页面URL")

# 等待表格加载完成
wait = WebDriverWait(driver, 10)
table = wait.until(EC.presence_of_element_located((By.TAG_NAME, "table")))
rows = table.find_elements(By.TAG_NAME, "tr")

# 遍历数据行(跳过表头,根据实际结构调整索引)
for row in rows[1:]:
    try:
        # 定位当前行的下拉按钮(替换成你页面实际的选择器,比如类名/XPath)
        dropdown_btn = row.find_element(By.CLASS_NAME, "dropdown-toggle-btn")
        # 用JS点击避免元素遮挡问题
        driver.execute_script("arguments[0].click();", dropdown_btn)
        
        # 等待展开内容可见(替换成实际展开内容的选择器)
        expanded_content = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "row-expanded-content")))
        
        # 提取当前行的所有数据,包括展开后的内容
        row_cells = row.find_elements(By.TAG_NAME, "td")
        row_data = [cell.text.strip() for cell in row_cells]
        row_data.append(expanded_content.text.strip())
        
        # 输出或保存数据
        print("完整行数据:", row_data)
        
        # 可选:关闭下拉面板,避免影响下一行操作
        close_btn = row.find_element(By.CLASS_NAME, "close-expanded-btn")
        driver.execute_script("arguments[0].click();", close_btn)
        
    except StaleElementReferenceException:
        # 处理元素过期异常,直接跳过当前行或重新定位
        continue

# 关闭浏览器
driver.quit()

关键注意事项

  • 选择器替换:务必将代码中的dropdown-toggle-btn、row-expanded-content等选择器,替换成你页面实际的元素类名、ID或XPath
  • 显式等待:必须使用WebDriverWait等待元素加载,避免因页面渲染延迟导致的元素查找失败
  • JS点击:当按钮被其他元素遮挡无法直接点击时,用execute_script执行JS点击更可靠
  • 异常处理:遍历行时容易出现StaleElementReferenceException,捕获后可选择跳过或重新定位当前行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:22:45