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

Python Selenium无法点击按钮展开页面数据表格的问题求解

问题说明

爬取mlb.com球队统计数据表格时,需点击展开按钮加载全量统计内容,现有Selenium代码运行后仅触发按钮悬停样式,未实际执行点击逻辑,无法加载完整表格。
复现问题的精简代码如下:

driver = webdriver.Chrome('/home/wsb/Downloads/chromedriver',options = options)
wait = WebDriverWait(driver, 30)

url_mlbcom_h = 'https://www.mlb.com/stats/team'

driver.get(url_mlbcom_h)

button = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="stats-app-root"]/section/section/div[1]/div[2]/div/div[1]/div/div[2]/button'))).click()
故障原因
  • 原代码用visibility_of_element_located仅判断元素在DOM中可见,此时按钮可能还未绑定完点击事件,或被页面懒加载的透明占位层、固定导航栏遮挡,普通click()触发的是上层遮挡元素的事件,只会触发按钮的hover样式,不会触发展开逻辑。
  • 该站点为React单页应用,DOM元素的交互事件需要页面资源完全加载、元素处于可交互状态时才能正常响应。
解决方法

优先用可点击条件等待+JS强制点击的方案,适配性最高:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome('/home/wsb/Downloads/chromedriver',options = options)
wait = WebDriverWait(driver, 30)
url_mlbcom_h = 'https://www.mlb.com/stats/team'
driver.get(url_mlbcom_h)

# 替换原有的可见性判断,等待元素进入可点击状态
expand_btn = wait.until(EC.element_to_be_clickable(
    (By.XPATH, '//*[@id="stats-app-root"]/section/section/div[1]/div[2]/div/div[1]/div/div[2]/button')
))
# 滚动到按钮所在位置,避免视口、固定导航栏遮挡
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", expand_btn)
# 用JS直接触发元素点击事件,绕过页面遮挡、事件拦截问题
driver.execute_script("arguments[0].click();", expand_btn)

# 点击后等待完整表格加载(这里判断最后一行数据出现,可根据实际页面结构调整)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'table.stats-table tr:last-child')))

如果站点有反爬检测拦截JS点击,可以用ActionChains模拟真人鼠标操作:

from selenium.webdriver.common.action_chains import ActionChains

expand_btn = wait.until(EC.element_to_be_clickable(
    (By.XPATH, '//*[@id="stats-app-root"]/section/section/div[1]/div[2]/div/div[1]/div/div[2]/button')
))
# 模拟鼠标移动到按钮、短暂停顿、点击的完整操作链
ActionChains(driver).move_to_element(expand_btn).pause(0.3).click().perform()
优化建议
  • 不建议使用从根节点开始的绝对XPath定位,页面结构微调就会失效,可以替换为基于按钮文本的相对定位,比如//button[contains(.,'Expand')],稳定性更高。
  • 点击操作后必须加表格加载完成的等待逻辑,否则会在表格未加载完成时就爬取,拿到残缺数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 22:24:19