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

Selenium Python问题:无法获取动态菜单中的li元素

问题修复方案

问题分析

你的代码存在几个关键问题导致无法获取尺码li元素:

  • URL缺失?符号,导致页面加载错误
  • 点击加入购物车按钮后未等待弹窗加载完成就直接查找元素
  • CSS选择器写法错误(多class选择器需用.连接而非空格)
  • 未处理元素可见性,可能导致点击失败

修正后的代码

import time
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.options import Options
from selenium.webdriver.common.action_chains import ActionChains

options = Options()
# options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=options)
# 修正URL,添加缺失的?
driver.get("https://www.zara.com/es/en/man-jeans-l659.html?v1=2351397")

# 处理地理位置弹窗
WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, 'button.zds-button.geolocation-modal__button.zds-button--primary'))
).click()

# 获取所有加入购物车按钮
buttons = WebDriverWait(driver, 10).until(
    EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'button.product-add-to-cart__button'))
)

for idx, button in enumerate(buttons):
    try:
        # 滚动到按钮可见位置
        ActionChains(driver).scroll_to_element(button).perform()
        # 点击按钮
        button.click()
        
        # 等待尺码弹窗加载完成,获取所有li元素
        size_items = WebDriverWait(driver, 10).until(
            EC.presence_of_all_elements_located(
                (By.CSS_SELECTOR, 'div.size-selector-list__wrapper.size-selector-list__wrapper--grid.size-selector-list__wrapper--open > ul.size-selector-list > li.size-selector-list__item')
            )
        )
        
        # 打印当前商品的尺码信息
        print(f"第{idx+1}个商品的尺码:")
        for item in size_items:
            print(item.text.strip())
        
        # 关闭弹窗,继续下一个商品
        close_btn = WebDriverWait(driver, 5).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, 'button.size-selector-list__close-button'))
        )
        close_btn.click()
        time.sleep(0.5)
    except Exception as e:
        print(f"处理第{idx+1}个商品时出错:{str(e)}")
        # 出错时尝试关闭弹窗
        try:
            close_btn = driver.find_element(By.CSS_SELECTOR, 'button.size-selector-list__close-button')
            close_btn.click()
        except:
            pass
        continue

driver.quit()

关键修改说明

  1. 修正URL:添加缺失的?符号,确保页面正常加载
  2. 等待机制:用WebDriverWait替代固定time.sleep,确保元素加载完成后再操作
  3. CSS选择器修正:多class选择器用.连接(如div.size-selector-list__wrapper.size-selector-list__wrapper--grid),避免后代选择器的错误匹配
  4. 元素可见性处理:通过scroll_to_element滚动到按钮位置,避免因元素不可见导致点击失败
  5. 异常处理:添加异常捕获,防止单个商品处理失败导致整个脚本终止,同时出错时尝试关闭弹窗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:00:05