如何使用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的按钮,得换对应的定位方式。
正确的定位方法
这里提供几种可行的方式:
- CSS选择器定位(推荐)
from selenium.webdriver.common.by import By # 匹配value属性等于MyButton的button元素 button = driver.find_element(By.CSS_SELECTOR, 'button[value="MyButton"]') button.click()
- XPath定位
from selenium.webdriver.common.by import By # 匹配value属性为MyButton的button节点 button = driver.find_element(By.XPATH, '//button[@value="MyButton"]') button.click()
- 旧版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
相关产品推荐
相关产品推荐

