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

如何使用Selenium各类选择器?定位value为MyButton的按钮

问题:如何用Selenium定位并点击指定value属性的按钮?

你提供的网页代码如下:

<html>
    <Button value="MyButton">press me!</button>
</html>

你尝试用class name定位按钮,代码如下:

eighth = driver.find_element_by_class_name("MyButtonClass")
eighth.click()

但出现错误提示(已翻译为中文):

Message: 找不到元素:无法定位元素:{"method":"css selector","selector":".MyButtonClass"}

问题原因

你用class_name定位,但目标按钮根本没有class属性,自然找不到元素。要定位的是value属性为MyButton的按钮,得换对应的定位方式。

正确的定位方法

这里提供几种可行的方式:

  1. CSS选择器定位(推荐)
from selenium.webdriver.common.by import By

# 匹配value属性等于MyButton的button元素
button = driver.find_element(By.CSS_SELECTOR, 'button[value="MyButton"]')
button.click()
  1. XPath定位
from selenium.webdriver.common.by import By

# 匹配value属性为MyButton的button节点
button = driver.find_element(By.XPATH, '//button[@value="MyButton"]')
button.click()
  1. 旧版Selenium写法(适用于3.x及以下版本)
    如果你的Selenium版本较低,也可以用旧的定位语法:
button = driver.find_element_by_xpath('//button[@value="MyButton"]')
button.click()

额外提示

如果页面加载有延迟,可添加显式等待避免元素未加载完成导致的定位失败:

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

# 等待10秒,直到按钮可点击
button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[value="MyButton"]'))
)
button.click()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:32:07