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

Selenium爬虫代码获取表格行数时崩溃的原因求助

问题描述

我是编程与爬虫领域的新手,因工作任务需要爬取世界泳联运动员信息网站。借助资料用Python和Selenium编写爬虫代码,无while循环时运行正常;加入while循环后,代码有时卡顿,但能执行到打印“complete”。目前核心问题是获取表格行数的代码行出现崩溃。尝试过添加等待时间、调整循环逻辑,曾遇到“Element is not clickable at point (X,Y)”错误,当前方法未出现该错误,但怀疑while循环存在问题,恳请帮忙排查原因。

代码如下:

while True:
    try:
        # Load more button path
        element = driver.find_element(By.XPATH, '//*[@id="main-content"]/section/div[2]/button')
        # Scroll down to button location
        driver.execute_script("arguments[0].scrollIntoView();", element)
        # Click on button 
        driver.execute_script("arguments[0].click();", element)
    except Exception as e:
        print (e)
        break
print ("Complete")

#Obtain the number of rows in body
rows = 1+len(driver.find_elements(By.XPATH, '//*[@id="main-content"]/section/div[1]/table/tbody/tr'))

排查与修复方案

1. 循环内缺乏等待,导致页面状态混乱

你的while循环高频重复点击“加载更多”,但页面数据加载需要时间,频繁操作会导致DOM未稳定,后续获取表格行时容易崩溃。

  • 修复:每次点击后添加显式等待,等待页面内容更新:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

while True:
    try:
        element = driver.find_element(By.XPATH, '//*[@id="main-content"]/section/div[2]/button')
        driver.execute_script("arguments[0].scrollIntoView();", element)
        driver.execute_script("arguments[0].click();", element)
        # 等待原按钮失效,确认新内容开始加载
        WebDriverWait(driver, 10).until(EC.staleness_of(element))
    except Exception as e:
        print(e)
        break

2. 获取表格行的逻辑存在漏洞

页面加载更多后,表格DOM可能处于临时未渲染状态,直接用固定XPATH获取行元素容易报错;另外你写的1+len(...)是误写,表格行数直接等于tr元素的数量。

  • 修复:给表格行获取逻辑添加显式等待,确保DOM稳定:
# 等待表格tbody元素加载完成
tbody = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '//*[@id="main-content"]/section/div[1]/table/tbody'))
)
# 获取最终行数
rows = len(tbody.find_elements(By.TAG_NAME, 'tr'))

3. 循环终止条件不严谨

当前仅靠“找不到按钮”抛出异常终止循环,但可能存在按钮可见但已不可点击(比如数据加载完毕)的情况,导致循环异常或无限执行。

  • 修复:增加按钮状态判断,确保仅在可点击时执行操作:
while True:
    try:
        element = WebDriverWait(driver, 5).until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="main-content"]/section/div[2]/button'))
        )
        # 按钮不可点击时终止循环
        if not element.is_enabled():
            break
        driver.execute_script("arguments[0].scrollIntoView();", element)
        driver.execute_script("arguments[0].click();", element)
        WebDriverWait(driver, 10).until(EC.staleness_of(element))
    except Exception as e:
        print(e)
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 16:42:15