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

Selenium Python中如何点击没有id属性的按钮

Selenium 无ID按钮的点击实现方案

Selenium 支持多种元素定位策略,无需依赖id属性即可精准定位目标元素,针对你给出的按钮,常用可落地的方法如下:

  • 文本匹配定位(最推荐,稳定性高)

    目标按钮的固定文本为Zum Warenkorb,用XPath直接匹配文本即可,只要页面内该按钮文本唯一,就不会定位出错:
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome()
    # 匹配完整文本
    add_cart_btn = driver.find_element(By.XPATH, '//button[text()="Zum Warenkorb"]')
    # 若文本前后存在空格,可改用模糊匹配
    # add_cart_btn = driver.find_element(By.XPATH, '//button[contains(text(), "Zum Warenkorb")]')
    add_cart_btn.click()
    
  • Class属性定位

    你提供的按钮带有多个class值,选择其中不会随页面更新变动的固定class使用即可,如果不确定哪个是固定值,优先选前缀规则的Buttonstyled__StyledButton-sc-140xkaw-1:
    # 单个class匹配
    add_cart_btn = driver.find_element(By.CLASS_NAME, 'Buttonstyled__StyledButton-sc-140xkaw-1')
    # 多class组合的CSS选择器,精准度更高
    add_cart_btn = driver.find_element(By.CSS_SELECTOR, 'button.Buttonstyled__StyledButton-sc-140xkaw-1.bbPePk')
    add_cart_btn.click()
    
    注意:如果class中带有随机生成的哈希后缀(比如每次版本更新都会变化的短字符串),不要使用该方法,优先选文本定位
  • 属性组合定位

    可以结合按钮的type属性、class特征组合写选择器,适合文本可能多语言切换的场景:
    # CSS选择器组合匹配type属性和class前缀
    add_cart_btn = driver.find_element(By.CSS_SELECTOR, 'button[type="button"][class*="Buttonstyled__StyledButton"]')
    add_cart_btn.click()
    

额外优化建议

如果点击时报元素未加载的错误,可以加显式等待,等元素可点击后再执行操作:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 最长等待10秒,直到元素可点击再操作
wait = WebDriverWait(driver, 10)
add_cart_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Zum Warenkorb"]')))
add_cart_btn.click()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:54:02