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

Selenium定位并点击加载更多按钮问题求助

Selenium抓取产品列表:加载更多按钮定位失败解决方案

问题背景

我正在使用Selenium抓取网站https://www.zonacriativa.com.br/harry-potter的产品列表,该页面共有116个产品,但仅显示部分内容,需点击底部“Carregar mais Produtos”(加载更多产品)按钮多次才能获取完整列表。不过该按钮无ID,类名过长,我尝试了以下几种定位方式均无效:

driver.find_element("xpath", "//button[text()='Carregar mais Produtos']").click()
driver.find_element("css selector", ".vtex-button__label.flex.items-center.justify-center.h-100.ph5").click()
driver.find_element(By.CLASS_NAME, "vtex-button.bw1.ba.fw5.v-mid.relative.pa0.lh-solid.br2.min-h-small.t-action--small.bg-action-primary.b--action-primary.c-on-action-primary.hover-bg-action-primary.hover-b--action-primary.hover-c-on-action-primary.pointer").click()

有效解决方案

1. 优化XPath文本匹配

按钮文本可能存在空格、换行或前后空白,用normalize-space统一处理后再匹配:

from selenium.webdriver.common.by import By

driver.find_element(By.XPATH, "//button[normalize-space(text())='Carregar mais Produtos']").click()

或者用contains模糊匹配文本(适合文本有细微变化的场景):

driver.find_element(By.XPATH, "//button[contains(text(), 'Carregar mais Produtos')]").click()

2. 精简CSS选择器

无需使用完整类名,挑选几个辨识度高的类组合定位:

driver.find_element(By.CSS_SELECTOR, "button.vtex-button.bg-action-primary").click()

如果按钮文本在内部span标签中,也可以先定位span再找父按钮:

driver.find_element(By.XPATH, "//span[normalize-space(text())='Carregar mais Produtos']/parent::button").click()

3. 增加显式等待确保按钮可点击

很多时候定位失败是因为按钮还未加载完成或未处于可点击状态,添加显式等待解决:

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

wait = WebDriverWait(driver, 10)
load_more_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space(text())='Carregar mais Produtos']")))
load_more_btn.click()

4. 循环点击直到所有产品加载完成

因为需要多次点击按钮,可通过循环判断按钮是否存在,直到无更多产品加载:

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

while True:
    try:
        # 等待按钮出现并可点击
        load_more_btn = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space(text())='Carregar mais Produtos']")))
        load_more_btn.click()
        # 等待产品加载完成,避免重复点击过快
        WebDriverWait(driver, 3).until(EC.staleness_of(load_more_btn))
    except TimeoutException:
        # 超时说明按钮已不存在,所有产品加载完成
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 18:45:32