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

使用Selenium点击按钮报错,寻求技术解决方案

问题解决:Selenium点击按钮报错NoSuchElementException

错误原因

你使用By.CLASS_NAME定位元素时传入了多个空格分隔的类名,但By.CLASS_NAME仅支持单个类名匹配,导致无法找到目标按钮,抛出NoSuchElementException。

解决方法

以下几种方式都可以正确定位到目标按钮:

方法1:使用CSS选择器(推荐)

CSS选择器支持多类名组合,直接把类名用点连接即可:

from selenium import webdriver
from selenium.webdriver.common.by import By

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('chromedriver',options=chrome_options)
wd.get("xxxxxx")

# 用CSS选择器定位多类名元素
button = wd.find_element(By.CSS_SELECTOR, ".VfPpkd-LgbsSe.VfPpkd-LgbsSe-OWXEXe-dgl2Hf.ksBjEc.lKxP2d.LQeN7.x0t5t") 
button.click()

方法2:使用单个独特类名

从HTML片段里挑一个辨识度高的单个类名(比如VfPpkd-LgbsSe-OWXEXe-dgl2Hf),用By.CLASS_NAME定位:

button = wd.find_element(By.CLASS_NAME, "VfPpkd-LgbsSe-OWXEXe-dgl2Hf")
button.click()

方法3:添加显式等待(避免页面未加载完成导致的定位失败)

如果页面加载较慢,建议加上显式等待,确保按钮可点击后再执行点击操作:

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

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('chromedriver',options=chrome_options)
wd.get("xxxxxx")

# 等待最多10秒,直到按钮可点击
button = WebDriverWait(wd, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, ".VfPpkd-LgbsSe.VfPpkd-LgbsSe-OWXEXe-dgl2Hf.ksBjEc.lKxP2d.LQeN7.x0t5t"))
)
button.click()

内容的提问来源于stack exchange,提问作者Alan Henrique Ferreira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:40:32